Let’s say I have a pandas df
like this:
JavaScript
x
7
1
| name | color of clothing | age |occupation|
2
| John | yellow | 34 | janitor |
3
| Carl | red | 27 | doctor |
4
| Claire | green | 33 | teacher |
5
| Lisa | blue | 21 | Student |
6
| ..| .| .| .|
7
I would like to transform it in a json format like this:
JavaScript
1
23
23
1
[
2
{ "name": "John,
3
"color of clothing": "yellow",
4
"age":"34",
5
"occupation": "janitor"
6
},
7
{ "name": "Carl",
8
"color of clothing": "red",
9
"age":"27",
10
"occupation": "doctor"
11
},
12
{ "name": "Claire",
13
"color of clothing": "green",
14
"age":"33",
15
"occupation": "teacher"
16
},
17
{ "name": "Lisa",
18
"color of clothing": "blue",
19
"age":"21",
20
"occupation": "student"
21
}
22
]
23
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:
JavaScript
1
13
13
1
{"0":{ "name": "John,
2
"color of clothing": "yellow",
3
"age":"34",
4
"occupation": "janitor"
5
}
6
},
7
"1":{ "name": "Carl",
8
"color of clothing": "red",
9
"age":"27",
10
"occupation": "doctor"
11
}}
12
13
Would be really thankful for any help!
Advertisement
Answer
Use df.to_dict('records')
JavaScript
1
7
1
>>> df
2
a b c d
3
0 1 1 1 1
4
1 2 2 2 2
5
>>> df.to_dict('records')
6
[{'a': 1, 'b': 1, 'c': 1, 'd': 1}, {'a': 2, 'b': 2, 'c': 2, 'd': 2}]
7