熊猫多重分组到JSON

时间:2019-10-11 08:28:44

标签: python json pandas

将以下数据帧转换为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"
            }
         ]
      }
   }
]

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

1 个答案:

答案 0 :(得分:0)

熊猫没有默认功能可以解决此问题。

此嵌套代码遍历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])
相关问题