tgordon18
tgordon18

Reputation: 1849

Pandas DataFrame Combine Certain Columns in Nested JSON

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).

Upvotes: 1

Views: 476

Answers (1)

BENY
BENY

Reputation: 323226

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

Upvotes: 2

Related Questions