将多索引熊猫数据框转换为JSON

时间:2020-03-30 20:50:46

标签: python pandas pandas-groupby multi-index

DataFrame来考虑熊猫MultiIndex

                    virtual_device_135 virtual_device_136
                              tag_5764           tag_5764
timestamp                                                
31/03/2020 02:10:30              -0.97                NaN
31/03/2020 02:10:35                NaN               0.98
31/03/2020 02:10:40              -0.97                NaN
31/03/2020 02:10:45                NaN              -0.98
31/03/2020 02:10:50              -0.97                NaN

上面的DataFrame需要转换为如下的json

bodyContent": [
        {
          "time": "31/03/2020 02:17:01",
          "tag_5764_virtual_device_135": -0.97
        },
        {
          "time": "31/03/2020 02:17:12",
          "tag_5764_virtual_device_135": -0.97
        },
        {
          "time": "31/03/2020 02:17:22",
          "tag_5764_virtual_device_135": -0.97
        },
        {
          "time": "31/03/2020 02:18:37",
          "tag_5764_virtual_device_136": -0.98
        },
        {
          "time": "31/03/2020 02:18:47",
          "tag_5764_virtual_device_136": -0.98
        },
        {
          "time": "31/03/2020 02:18:57",
          "tag_5764_virtual_device_136": -0.98
        }
]

当前,我正在拆分DF,然后重命名该列,然后合并它,然后转换为json。

我可以在熊猫中使用更好的方法吗?

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

我发现可以通过以下方式完成

如果DataFrame是df:

df.columns = ['_'.join(col) for col in df.columns]
df.reset_index(inplace=True)

df_list = json.loads(df.to_json(orient='records'))

for each in df_list:
    body_content_list.append(each)

希望这对某人有用。

答案 1 :(得分:0)

df.columns = ['_'.join(col[::-1]) for col in df.columns]
df = df.reset_index().rename(columns = {'timestamp': 'time'})
jsonbody = list({k: {k1:v1 for k1,v1 in v.items() if pd.notnull(v1)} \
           for k, v in df.to_dict(orient= 'index').items()}.values())