首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从Python中的JSON字符串中删除冗余元素

如何从Python中的JSON字符串中删除冗余元素
EN

Stack Overflow用户
提问于 2022-09-07 15:41:41
回答 1查看 41关注 0票数 0

下面的JSON字符串是从Pandas数据框架转换而来的。

代码语言:javascript
复制
[
   {
      "ID":"1",
      "Salary1":69.43,
      "Salary2":513.0,
      "Date":"2022-06-09",
      "Name":"john",
      "employeeId":12,
      "DateTime":"2022-09-0710:57:55"
   },
   {
      "ID":"2",
      "Salary1":691.43,
      "Salary2":5123.0,
      "Date":"2022-06-09",
      "Name":"john",
      "employeeId":12,
      "DateTime":"2022-09-0710:57:55"
   }
]

我想将上面的JSON更改为下面的格式。

代码语言:javascript
复制
[
   {
      "Date":"2022-06-09",
      "Name":"john",
      "DateTime":"2022-09-0710:57:55",
      "employeeId":12,
      "Results":[
         {
            "ID":1,
            "Salary1":69.43,
            "Salary2":513
         },
         {
            "ID":"2",
            "Salary1":691.43,
            "Salary2":5123
         }
      ]
   }
]

请告诉我如何在Python中实现这一点。

原始Dataframe:

代码语言:javascript
复制
ID  Salary1  Salary2  Date        Name  employeeId  DateTime   
1   69.43     513.0   2022-06-09  john   12         2022-09-0710:57:55
2   691.43    5123.0  2022-06-09  john   12         2022-09-0710:57:55

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-07 18:23:11

正如@Harsha所指出的,您可以修改another question的一个答案,只需做一些小小的调整,就可以使其适用于OP的情况:

代码语言:javascript
复制
(
  df.groupby(["Date","Name","DateTime","employeeId"])[["ID","Salary1","Salary2"]]

    # to_dict(orient="records") - returns list of rows, where each row is a dict,
    # "oriented" like [{column -> value}, … , {column -> value}]
    .apply(lambda x: x.to_dict(orient="records")) 

    # groupBy makes a Series: with grouping columns as index, and dict as values. 
    # This structure is no good for the next to_dict() method. 
    # So here we create new DataFrame out of grouped Series, 
    # with Series' indexes as columns of DataFrame,
    # and also renamimg our Series' values to "Results" while we are at it.
    .reset_index(name="Results")

    # Finally we can achieve the desired structure with the last call to to_dict():
    .to_dict(orient="records")
)
# [{'Date': '2022-06-09', 'Name': 'john', 'DateTime': '2022-09-0710:57:55', 'employeeId': 12, 
# 'Results': [
#   {'ID': 1, 'Salary1': 69.43, 'Salary2': 513.0}, 
#   {'ID': 2, 'Salary1': 691.43, 'Salary2': 5123.0}
# ]}]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73638269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档