【发布时间】:2017-05-27 08:26:58
【问题描述】:
我有一个如下所示的 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
}
]
}
]
}
"name" 和 "children" 应该如上所示出现(即使它们在 DataFrame 中没有作为列出现)。
我对此并不陌生,对如何获得此输出没有太多想法。我在这里搜索并浏览了几个类似的帖子。
我专门研究了以下帖子:Userdefined Json Format From Pandas DataFrame,这与我想要的类似。这篇文章中提到的答案虽然不起作用。我不知道如何从那里继续获得我想要的输出。
您能否指导我如何实现这一目标?
【问题讨论】:
-
这可以帮助您入门:
df.groupby('Category').apply(lambda g: g.drop('Category', axis=1).to_dict(orient='records')).to_dict() -
@IanS 感谢您的帮助...
-
很好,很高兴我能帮上忙!
标签: json python-3.x pandas