【问题标题】:Pandas multiple group by to json熊猫多个分组到json
【发布时间】:2020-02-08 17:48:58
【问题描述】:

我在将以下数据帧转换为 JSON 结构时遇到了一些问题。我已经尝试了一些事情,但不能完全到达最后一点。 所以我有一个包含以下内容的数据框

  serialNumber |    date    | part  | value | name
 --------------|------------|-------|-------|---------------- 
  ABC0001      | 01/10/2019 | Part1 | ABC1  | ABC            
  ABC0001      | 01/10/2019 | Part1 | ABC2  | XYZ            
  ABC0001      | 02/10/2019 | Part2 | ABC3  | ASF            
  ABC0001      | 02/10/2019 | Part2 | ABC4  | TSR    

并且需要它的格式为

  { "SerialNumber": "ABC001",
    "detail": [  { "part": "Part1",
                   "date":"01/10/2019",
                   "extras": [  { "value": "ABC1",
                                  "name": "ABC"
                                },
                                { "value": "ABC2",
                                  "name": "XYZ"
                                }]
                 },
                 { "part": "Part2",
                   "date":"02/10/2019",
                   "extras": [   { "value": "ABC3",
                                  "name": "ASF"
                                },
                                { "value": "ABC4",
                                  "name": "TSR"
                                }]
              ]
     }  

所以分组序列号,然后是数据和部分,然后是值和名称。 我看了一些答案herehere,最后一个帮助很大

df.groupby(['serialNumber', 'Part']).apply(
        lambda r: r[['Value', 'identifierName']].to_dict(orient='records')
    ).unstack('serialNumber').apply(lambda s: [
        {s.index.name: idx, 'detail=': value}
        for idx, value in s.items()]
    ).to_json(orient='records')

这给了我

[
   {
      "ABC0001":{
         "Part":"Part1",
         "detail=":[
            {
               "Value":"ABC1",
               "identifierName":"ABC"
            },
            {
               "Value":"ABC2",
               "identifierName":"XYZ"
            }
         ]
      }
   },
   {
      "ABC0001":{
         "Part":"Part2",
         "detail=":[
            {
               "Value":"ABC3",
               "identifierName":"ASF"
            },
            {
               "Value":"ABC4",
               "identifierName":"TSR"
            }
         ]
      }
   }
]

但是当我添加日期时出现故障,并且不显示序列号标签 建议??提示?

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

    pandas 中没有默认函数来解决这个问题。

    此嵌套代码遍历MultIndex 的每一层,将层添加到字典中,直到将最深层分配给Series 值。

    这适用于任意数量的嵌套折叠:

    grouped = df.set_index(['serialNumber', 'Part'])

    import json
    
    levels = grouped.ndim
    dicts = [{} for i in range(levels)]
    last_index = None
    
    for index,value in enumerate(grouped.itertuples(), 1):
    
        if not last_index:
            last_index = index
    
        for (ii,(i,j)) in enumerate(zip(index, last_index)):
            if not i == j:
                ii = levels - ii -1
                dicts[:ii] =  [{} for _ in dicts[:ii]]
                break
    
        for i, key in enumerate(reversed(index)):
            dicts[i][key] = value
            value = dicts[i]
    
        last_index = index
    
    
    result = json.dumps(dicts[-1])
    

    【讨论】:

    • 感谢您的更新,我刚刚进行了测试并得到了“无法访问“DataFrameGroupBy”对象的可调用属性“itertuples”,请尝试使用“应用”方法”我只是在阅读csv 文件转换成数据框,然后运行上面的代码?有什么建议吗?
    • 是的,我理解并解决了这个问题
    • 对不起,还有一个,我尝试调试它,现在得到 ValueError: too many values to unpack (expected 2)
    • @Jonee 哪一行?
    • for index, value in grouped.itertuples()
    猜你喜欢
    • 2016-03-14
    • 2017-05-24
    • 2016-07-03
    • 2016-05-23
    • 1970-01-01
    • 2021-10-28
    • 2017-09-10
    • 2016-12-06
    • 2018-12-24
    相关资源
    最近更新 更多