我有一個pandas資料框
ID Name Score Score_scale
1 ABC 1 5
2 DEF 2 5
3 GHI 3 5
我需要將其轉換為以下格式
ID Name Score
1 ABC [{'score_scale':5, 'score':1}]
2 DEF [{'score_scale':5, 'score':2}]
3 GHI [{'score_scale':5, 'score':3}]
需要你的幫助。謝謝你。
uj5u.com熱心網友回復:
第一個想法是 use DataFrame.to_dict,但不創建嵌套串列:
df['Score'] = df[['Score','Score_scale']].to_dict('records')
df = df.drop('Score_scale', 1)
print (df)
ID Name Score
0 1 ABC {'Score': 1, 'Score_scale': 5}
1 2 DEF {'Score': 2, 'Score_scale': 5}
2 3 GHI {'Score': 3, 'Score_scale': 5}
如果需要嵌套值:
df['Score'] = [[x] for x in df[['Score','Score_scale']].to_dict('records')]
df = df.drop('Score_scale', 1)
print (df)
ID Name Score
0 1 ABC [{'Score': 1, 'Score_scale': 5}]
1 2 DEF [{'Score': 2, 'Score_scale': 5}]
2 3 GHI [{'Score': 3, 'Score_scale': 5}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/465573.html
