简体   繁体   中英

How can I transform a pandas df to this kind of json structure?

Let's say I have a pandas df like this:

| name   | color of clothing | age |occupation|
| John   | yellow            | 34  | janitor  |
| Carl   | red               | 27  | doctor   |
| Claire | green             | 33  | teacher  |
| Lisa   | blue              | 21  | Student  |
|........|...................| ....|..........|

I would like to transform it in a json format like this:

[
{ "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"
}
]

How can I do this? The nearest match I had was using df.to_json(orient="index") but what I've got was a structure like this:

{"0":{ "name": "John,
"color of clothing": "yellow",
"age":"34",
"occupation": "janitor"
}
},
"1":{ "name": "Carl",
"color of clothing": "red",
"age":"27",
"occupation": "doctor"
}}
...

Would be really thankful for any help!

Use 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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM