我有一个像下面这样的Pandas DataFrame:
ID | Category | Description | Score
-----------------------------------
1 | 1 | Desc 1 | 20.0
2 | 1 | Desc 2 | 30.0
3 | 1 | Desc 3 | 30.0
4 | 2 | Desc 4 | 50.0
5 | 2 | Desc 5 | 50.0
6 | 3 | Desc 6 | 55.0
从这个DataFrame中,我必须得到以下格式的JSON输出:
{
"name": "Category",
"children":
[
{
"name": "1",
"children":
[
{
"name": "ID: 1",
"Description": "Desc 1",
"Score": 20.0
}
{
"name": "ID: 2",
"Description": "Desc 2",
"Score": 30.0
}
{
"name": "ID: 3",
"Description": "Desc 3",
"Score": 30.0
}
]
},
{
"name": "2",
"children":
[
{
"name": "ID: 4",
"Description": "Desc 4",
"Score": 50.0
}
{
"name": "ID: 5",
"Description": "Desc 5",
"Score": 50.0
}
]
}
{
"name": "3",
"children":
[
{
"name": "ID: 6",
"Description": "Desc 6",
"Score": 55.0
}
]
}
]
}
"名称"和#34;孩子"应该如上所示出现(即使这些不作为DataFrame中的列出现) 我是新手,并不知道如何获得这个输出。我在这里搜索并经历了几个类似的帖子 我特意调查了以下帖子:Userdefined Json Format From Pandas DataFrame这与我想要的类似。这篇文章中提到的答案虽然不起作用。我无法弄清楚如何继续前进以获得我想要的输出 你能指导我如何实现这个目标吗?
答案 0 :(得分:1)
谢谢@IanS
我从您的代码中获取了想法,并使用下面的代码片段来获取输出:
cList = []
groupDict = outputDF.groupby('Category').apply(lambda g: g.drop('Category', axis=1).to_dict(orient='records')).to_dict()
for key, value in groupDict.items():
cList.append(dict(name=str(key)), children=value)
finalJSON = dict(name='Category', children=cList)
finalJSON = json.dumps(finalJSON)
print(finalJSON)