如何使用数组中的特定列将数据输出到JSON
我需要逐行将一些结果从Pandas数据帧输出到JSON。我已经整理好了导出,效果很好,它是将某些列放入数组的精细细节。比如说如何使用数组中的特定列将数据输出到JSON,json,python-3.x,pandas,dataframe,Json,Python 3.x,Pandas,Dataframe,我需要逐行将一些结果从Pandas数据帧输出到JSON。我已经整理好了导出,效果很好,它是将某些列放入数组的精细细节。比如说 Id customerId baseValue targetValue 1客户1482306 2客户2 723 420 3客户3 279 161 4客户4162774 对于Id 1,我需要以的样式导出 {“Id”:“1”, “customerId”:“Customer1”, “结果”:[{“基本值”:482}, {“targetValue”:306} ] } 我被困在
Id customerId baseValue targetValue
1客户1482306
2客户2 723 420
3客户3 279 161
4客户4162774
对于Id 1,我需要以的样式导出
{“Id”:“1”,
“customerId”:“Customer1”,
“结果”:[{“基本值”:482},
{“targetValue”:306}
]
}
我被困在这一点上:
“结果”:[{“baseValue”:482},
{“targetValue”:306}
]
有什么建议吗
谢谢您是否尝试过:
df.to_json(orient=“index”)
您是否尝试过:
df.to_json(orient=“index”)
您可以尝试以下方法在数据框中创建“结果”列:
df.assign(results = df.apply(lambda x: [x[['baseValue','targetValue']].to_dict()], axis=1)).drop(['baseValue','targetValue'], axis=1).to_dict(orient='records')
输出:
[{'Id': 1,
'customerId': 'Customer1',
'results': [{'baseValue': 482, 'targetValue': 306}]},
{'Id': 2,
'customerId': 'Customer2',
'results': [{'baseValue': 723, 'targetValue': 420}]},
{'Id': 3,
'customerId': 'Customer3',
'results': [{'baseValue': 279, 'targetValue': 161}]},
{'Id': 4,
'customerId': 'Customer4',
'results': [{'baseValue': 162, 'targetValue': 774}]}]
您可以尝试以下方法在数据框中创建“结果”列:
df.assign(results = df.apply(lambda x: [x[['baseValue','targetValue']].to_dict()], axis=1)).drop(['baseValue','targetValue'], axis=1).to_dict(orient='records')
输出:
[{'Id': 1,
'customerId': 'Customer1',
'results': [{'baseValue': 482, 'targetValue': 306}]},
{'Id': 2,
'customerId': 'Customer2',
'results': [{'baseValue': 723, 'targetValue': 420}]},
{'Id': 3,
'customerId': 'Customer3',
'results': [{'baseValue': 279, 'targetValue': 161}]},
{'Id': 4,
'customerId': 'Customer4',
'results': [{'baseValue': 162, 'targetValue': 774}]}]