如何将 pandas df 转换为这种 json 结构?
How can I transform a pandas df to this kind of json structure?
假设我有这样一个 pandas 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"
}}
...
非常感谢您的帮助!
使用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}]
假设我有这样一个 pandas 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"
}}
...
非常感谢您的帮助!
使用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}]