我有一个熊猫数据框:
Df = pd.DataFrame({ 'FirstId': 123,
'SecondId': 345,
'ThirdId': 678,
'country' : 'Gambia',
'type' : 'Major',
'Version' : 3,
'original': 'NotOriginal',
'Score1': 12.3,
'Score2': 30.4
})
我想要的 json 应该是这样的:
{
"FirstId": 123,
"SecondId": 345,
"ThirdId": 678,
"country": "Gambia",
"algorithmType": {
"type": "Major",
"Version": 3
},
"original": "NotOriginal",
"Score1": 12.3,
"Score2": 30.4
}
我试过了:
js = (Df.groupby(['FirstId','SecondId','ThirdId','country','original', 'Score1', 'Score2'])
.apply(lambda x: x[['type','Version']].to_dict('records'))
.reset_index()
.rename(columns={0:'algorithmType'})
.to_json(orient='records', lines=True))
print(json.dumps(json.loads(js), indent=2))
我的尝试没有给出我想要的顺序,而是将 'algorithmType' 作为数组而不是我想要的对象。
答案 0 :(得分:1)
如果你有这样的 df:
FirstId SecondId ThirdId country type Version original Score1 \
0 123 345 678 Gambia Major 3 NotOriginal 12.3
Score2
0 30.4
尝试:
json_output = df.assign(algorithmType=df[['type', 'Version']].to_dict(
'records')).drop(['type', 'Version'], 1).to_dict('records')
输出:
[{'FirstId': 123,
'SecondId': 345,
'ThirdId': 678,
'country': 'Gambia',
'original': 'NotOriginal',
'Score1': 12.3,
'Score2': 30.4,
'algorithmType': {'type': 'Major', 'Version': 3}}]
更新答案:
json_output = df.assign(algorithmType=df[['type', 'Version']].to_dict(
'records')).drop(['type', 'Version'], 1)[['FirstId', 'SecondId', 'ThirdId', 'country', 'algorithmType',
'original', 'Score1', 'Score2']].to_dict('records')
输出:
[{'FirstId': 123,
'SecondId': 345,
'ThirdId': 678,
'country': 'Gambia',
'algorithmType': {'type': 'Major', 'Version': 3},
'original': 'NotOriginal',
'Score1': 12.3,
'Score2': 30.4}]