本文介绍了 pandas 数据框到嵌套JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将Pandas Dataframe转换为JSON对象.我的数据框包含以下格式的数据:
I am trying to convert a Pandas Dataframe to a JSON object. My Dataframe contains data in the following format:
student date grade course
0 Student_1 2017-06-25 93 ENGLISH
1 Student_2 2017-06-25 83 ENGLISH
2 Student_1 2017-06-25 93 MATH
3 Student_2 2017-06-25 83 MATH
4 Student_1 2017-06-26 90 MATH
5 Student_2 2017-06-26 85 MATH
6 Student_1 2017-06-26 96 ENGLISH
7 Student_2 2017-06-26 99 ENGLISH
我想将其转换为以下格式的JSON对象:
I want to convert it to a JSON object in the following format:
[
{'ENGLISH': [
{
'date' : '2017-06-25',
'Student_1' : 93,
'Student_2' : 83
},
{
'date' : '2017-06-26',
'Student_1' : 96,
'Student_2' : 89
}]
},
{'MATH': [
{
'date' : '2017-06-25',
'Student_1' : 93,
'Student_2' : 83
},
{
'date' : '2017-06-26',
'Student_1' : 90,
'Student_2' : 85
}]
}
]
一个简单的.to_json()
调用对我来说没有帮助.无论如何,我可以在Pandas中以所需格式创建JSON对象吗?
A simple .to_json()
call did not do the trick for me. Is there anyway I can create the JSON object in the required format in Pandas?
推荐答案
您可以先定义一个将子组转换为json的函数,然后将该函数应用于每个组,然后将子组json合并为单个json对象.
You can first define a function to convert sub-groups to json, then apply this function to each group, and then merge sub-group jsons to a single json object.
def f(x):
return (dict({'date':x.date.iloc[0]},**{k:v for k,v in zip(x.student,x.grade)}))
(
df.groupby(['course','date'])
.apply(f)
.groupby(level=0)
.apply(lambda x: x.tolist())
.to_dict()
)
Out[1006]:
{'ENGLISH': [{'Student_1': 93, 'Student_2': 83, 'date': '2017-06-25'},
{'Student_1': 96, 'Student_2': 99, 'date': '2017-06-26'}],
'MATH': [{'Student_1': 93, 'Student_2': 83, 'date': '2017-06-25'},
{'Student_1': 90, 'Student_2': 85, 'date': '2017-06-26'}]}
这篇关于 pandas 数据框到嵌套JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!