我有一个来自我的python代码的数据框:
emp_id skillset experience emp_name department
0 1120 java 7 Gary Lobortis
1 1120 python 1 Gary Lobortis
2 1120 Analytics 7 Gary Lobortis
3 1122 Oracle 3 Prescott Velit
4 1129 AWS 7 Kevin Sed
5 1122 java 3 Prescott Velit
请参阅结果表格的Image:
我想从此数据框输出嵌套的JSON。
答案 0 :(得分:0)
假设您的DataFrame名称为df
,以下内容可为您提供所需内容。
import json
j = (df.groupby(['emp_id','emp_name','department'], as_index=False)
.apply(lambda x: x[['skillset','experience']].to_dict('r'))
.reset_index()
.rename(columns={0:'skills'})
.to_json(orient='records'))
print(json.dumps(json.loads(j), indent=2, sort_keys=False))
输出:
[
{
"emp_id": 1120,
"emp_name": "Gary",
"department": "Lobortis",
"skills": [
{
"skillset": "java",
"experience": 7
},
{
"skillset": "python",
"experience": 1
},
{
"skillset": "Analytics",
"experience": 7
}
]
},
{
"emp_id": 1122,
"emp_name": "Prescott",
"department": "Velit",
"skills": [
{
"skillset": "Oracle",
"experience": 3
},
{
"skillset": "java",
"experience": 3
}
]
},
{
"emp_id": 1129,
"emp_name": "Kevin",
"department": "Sed",
"skills": [
{
"skillset": "AWS",
"experience": 7
}
]
}
]