【发布时间】:2023-03-18 11:09:01
【问题描述】:
我正在使用 pandas,并且我在数据框上应用了 groupby。现在我需要将此数据帧转换为 Json 文件。
数据框(名称 = 分组):
| student_id | stuent_name | course_id | subject_name | teacher | weight_score | total_average |
|---|---|---|---|---|---|---|
| 1 | A | 1 | Biology | Mr.D | 90.1 | 72.0333 |
| 2 | History | Mrs.P | 51.8 | 72.0333 | ||
| 3 | Math | Mrs.C | 74.2 | 72.0333 | ||
| 2 | B | 1 | Biology | Mr.D | 50.1 | 62.1500 |
| 3 | Math | Mrs.C | 74.2 | 62.1500 | ||
| 3 | C | 1 | Biology | Mr.D | 90.1 | 72.0333 |
| 2 | History | Mrs.P | 51.8 | 72.0333 | ||
| 3 | Math | Mrs.C | 74.2 | 72.0333 |
数据帧类型:
type(grouped)
pandas.core.frame.DataFrame
当我尝试检索列时,它只允许我获取两列。我想要所有带有列名的值。
grouped.columns
Index(['weighted_score', 'total_average'], dtype='object')
我需要这样的输出:
[{
"students": [
{
"id": 1,
"name": "A",
"totalAverage": 72.03,
"courses": [
{
"id": 1,
"name": "Biology",
"teacher": "Mr. D",
"courseAverage": 90.1
},
{
"id": 3,
"name": "Math",
"teacher": "Mrs. C",
"courseAverage": 74.2
},
{
"id": 2,
"name": "History",
"teacher": "Mrs. P",
"courseAverage": 51.8
}
]
},
{
"id": 2,
"name": "B",
"totalAverage": 62.15,
"courses": [
{
"id": 1,
"name": "Biology",
"teacher": "Mr. D",
"courseAverage": 50.1
},
{
"id": 3,
"name": "Math",
"teacher": "Mrs. C",
"courseAverage": 74.2
}
]
},
{
"id": 3,
"name": "C",
"totalAverage": 72.03,
"courses": [
{
"id": 1,
"name": "Biology",
"teacher": "Mr. D",
"courseAverage": 90.1
},
{
"id": 2,
"name": "History",
"teacher": "Mrs. P",
"courseAverage": 51.8
},
{
"id": 3,
"name": "Math",
"teacher": "Mrs. C",
"courseAverage": 74.2
}
]
}
]
}]
【问题讨论】:
标签: python json pandas pandas-groupby data-analysis