![](/img/trans.png)
[英]Get nested JSON from pandas dataframe grouped by multiple columns
[英]Pandas grouping by multiple columns to get a multi nested Json
我有一个 dataframe 如下所示:
Lvl1 lvl2 lvl3 lvl4 lvl5
x 1x 3xx 1 "text1"
x 1x 3xx 2 "text2"
x 1x 3xx 3 "text3"
x 1x 4xx 4 "text4"
x 2x 4xx 5 "text5"
x 2x 4xx 6 "text6"
y 2x 5xx 7 "text7"
y 3x 5xx 8 "text8"
y 3x 5xx 9 "text9"
y 3x 6xx 10 "text10"
y 4x 7xx 11 "text11"
y 4x 7xx 62 "text12"
y 4x 8xx 62 "text13"
z
z
z
w
w
w
I would like to convert to nested json so it looks like this:
[{
"x":{
"1x":[{
"3xx": [
{
lvl4: 1
lvl5: "text1"
},
{
lvl4: 2
lvl5: "text2"
},
{
lvl4: 3
lvl5: "text3"
}],
"4xx": [
{
lvl4: 4
lvl5: "text4"
}],
"2x":[{
"4xx": [
{
lvl4: 5
lvl5: "text5"
},
{
lvl4: 6
lvl5: "text6"
}],
"5xx": [
{
lvl4: 7
lvl5: "text7"
}],
}]
. . .
我在这里使用示例作为开始,但我需要缩进的 lvl1、lvl2、lvl3,如显示的数据所示。 参考示例返回同一级别的 lvl1、lvl2、lvl3。
另外,我需要将 lvl 的密钥作为 lvl 值。 例如“x”而不是“lvl1”。
[{
"x":{
谢谢
根据预期的 output,您可以使用三个嵌套的groupby
和使用to_dict
来做到这一点。 可能有更好的方法,但至少是一个开始:
[df.groupby('Lvl1')\
.apply(lambda x: x.groupby('lvl2')\
.apply(lambda x: [x.groupby('lvl3')
.apply(lambda x: x[['lvl4','lvl5']].to_dict('r')
).to_dict()]
).to_dict()
).to_dict()]
[{'x': {'1x': [{'3xx': [{'lvl4': 1, 'lvl5': '"text1"'},
{'lvl4': 2, 'lvl5': '"text2"'},
{'lvl4': 3, 'lvl5': '"text3"'}],
'4xx': [{'lvl4': 4, 'lvl5': '"text4"'}]
}],
'2x': [{'4xx': [{'lvl4': 5, 'lvl5': '"text5"'},
{'lvl4': 6, 'lvl5': '"text6"'}]}]},...
我只是对确切的外部格式有疑问
编辑感谢@Trenton McKinney,看来如果你这样做:
df['lvl5'] = df['lvl5'].str.strip('"')
test = [df.groupby('Lvl1')\
.apply(lambda x: x.groupby('lvl2')\
.apply(lambda x: [x.groupby('lvl3')
.apply(lambda x: x[['lvl4','lvl5']].to_dict('r')
).to_dict()]
).to_dict()
).to_dict()]
import json
json_res = list(map(json.dumps, test))
那么json_res
可以满足 json 的需求
test
保存为双引号 json 格式with open('data.json', 'w') as f:
json.dump(test, f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.