假設我有一個df這樣的熊貓:
| name | color of clothing | age |occupation|
| John | yellow | 34 | janitor |
| Carl | red | 27 | doctor |
| Claire | green | 33 | teacher |
| Lisa | blue | 21 | Student |
|........|...................| ....|..........|
我想把它轉換成這樣的json格式:
[
{ "name": "John,
"color of clothing": "yellow",
"age":"34",
"occupation": "janitor"
},
{ "name": "Carl",
"color of clothing": "red",
"age":"27",
"occupation": "doctor"
},
{ "name": "Claire",
"color of clothing": "green",
"age":"33",
"occupation": "teacher"
},
{ "name": "Lisa",
"color of clothing": "blue",
"age":"21",
"occupation": "student"
}
]
我怎樣才能做到這一點?我使用的是最近的匹配,df.to_json(orient="index")但我得到的是這樣的結構:
{"0":{ "name": "John,
"color of clothing": "yellow",
"age":"34",
"occupation": "janitor"
}
},
"1":{ "name": "Carl",
"color of clothing": "red",
"age":"27",
"occupation": "doctor"
}}
...
非常感謝您的幫助!
uj5u.com熱心網友回復:
采用df.to_dict('records')
>>> df
a b c d
0 1 1 1 1
1 2 2 2 2
>>> df.to_dict('records')
[{'a': 1, 'b': 1, 'c': 1, 'd': 1}, {'a': 2, 'b': 2, 'c': 2, 'd': 2}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468425.html
