场景:我有一个包含一行数据的数据框。每列代表一年,并具有相关值。我尝试使用此 df 中的数据创建一个 json 样式结构以传递给 API 请求。post。
样本 DF:
+-------+-------+-------+-------+-------+-------+-------------+-------------+-------------+-------------+-------------+-------------+
| | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 | 2026 | 2027 | 2028 | 2029 | 2030 |
+-------+-------+-------+-------+-------+-------+-------------+-------------+-------------+-------------+-------------+-------------+
| Total | 23648 | 20062 | 20555 | 22037 | 26208 | 28224.88801 | 29975.87934 | 31049.01582 | 32170.68853 | 33190.35298 | 34031.93951 |
+-------+-------+-------+-------+-------+-------+-------------+-------------+-------------+-------------+-------------+-------------+
JSON 样式结构示例:
parameters = {
"first_Id":first_id,
"version":2,
"overrideData":[
{
"period":2024,
"TOTAL":101.64,
},
{
"period":2025,
"TOTAL":104.20,
}
]
}
问题:使用 Df 中的数据填充和扩展 JSON 样式对象的最佳方法是什么?我尝试了以下方法,但这只会分隔两行,一行用于总计,一行用于期间,这不会导致配对需求:
parameters = {}
parameters['first_Id'] = first_id
parameters['version'] = 2
parameters['overrideData'] = {
}
parameters['overrideData']['total'] = test_input.iloc[0].tolist()
parameters['overrideData']['period'] = list(test_input.columns)
其结果是:
{
"companyId": 11475,
"version": 2,
"overrideData": {
"TOTAL": [
23647.999999999996,
20061.999999999996,
20555,
22036.999999999996,
26207.999999999993,
28224.88800768,
29975.879336500002,
31049.015816740008,
32170.68852577,
33190.3529754,
34031.93951397
],
"period": [
2020,
2021,
2022,
2023,
2024,
2025,
2026,
2027,
2028,
2029,
2030
]
}
}