简体   繁体   English

如何将多索引数据帧(按多列分组的数据帧)转换为嵌套的 json

[英]How to convert a multi-indexed dataframe, a dataframe grouped by multi columns to nested json

My Pandas Series, which I got from applying groupby operation on DataFrame with columns 'var' and 'month' and applying sum on the corresponding data looks like this ('var' and 'month' are indexes below) :我的 Pandas 系列是通过在 DataFrame 上应用 groupby 操作获得的,其中包含“var”和“month”列并对相应数据应用 sum 看起来像这样(“var”和“month”是下面的索引):

    var  month
X   Feb     -0.061575
    Jan      1.366478
Y   Feb     -1.310896
Z   Apr      0.053076
    Feb      1.292415
    Mar      0.375144
P   Feb      1.241288
    Mar      0.613453

What I want a format of JSON created from the above DataFrame like below:我想要一种从上面的 DataFrame 创建的 JSON 格式,如下所示:

'data':[{'label': 'X', 'data': ['Jan': 1.366478, 'Feb': -0.061575]}, ... ]

I know the basic pandas .to_json() may not work here.我知道基本的熊猫.to_json()在这里可能不起作用。 Probably a combination of list comprehension, lambda function etc. can work here?可能列表理解、lambda 函数等的组合可以在这里工作?

The closest I could think of is :我能想到的最接近的是:

dict = {k: df[k].to_dict() for k in df.index.levels[0]}

This produce {'X': {'Feb': -0.06157474257929787, 'Jan': 1.366478487212244},'Y': ...}这产生{'X': {'Feb': -0.06157474257929787, 'Jan': 1.366478487212244},'Y': ...}

Any help is appreciated.任何帮助表示赞赏。

Thanks谢谢

'data':[{'label': 'X', 'data': ['Jan': 1.366478, 'Feb': -0.061575]}, ... ]

This is an invalid json.这是一个无效的 json。 The inner list doesn't make sense内部列表没有意义

For me the solution I found is below piece of code (Assuming group_data holds the already grouped by data on a DataFrame).对我来说,我找到的解决方案是下面的一段代码(假设 group_data 保存了已经按数据分组的数据帧)。

group_dict = {k: group_data[k].to_dict() for k in group_data.index.levels[0]}
group_list = []
for k, v in group_dict.items():
    dict = {'label': k, 'data': v}
    group_list.append(dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM