Let's say you have a pandas DataFrame that looks like this:
A1a A1b A2a A2b … B1a …
0.25 0.75 0.10 0.5 1
… … … … …
And you want to output a JSON list of objects (one object for each row) that looks like this:
[
{
A: {
1: {
a: 0.25,
b: 0.75
},
2: {
a: 0.1,
b: 0.5,
...
},
...
},
B: {
1: {
a: 1
},
...
},
...
},
...
]
What's the best way to do this?
There are obviously a lot of pandas/nested JSON questions on here, but I think this is different because I'm trying to nest specific columns within the same row, rather than grouping rows that have the same values in columns (like in this example).
Since you link the page , I will borrow the recur_dictify
function from the accepted answer in that link
#make your df columns become multiple index
df.columns=pd.MultiIndex.from_tuples(df.columns.map(list).map(tuple))
A
1 2
a b a b
0 0.25 0.75 0.1 0.5
#Then we apply the function
recur_dictify(df.T.reset_index())
{'A': {'1': {'a': 0.25, 'b': 0.75}, '2': {'a': 0.1, 'b': 0.5}}}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments