1

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

0

1 Answer 1

2

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}}} 
Sign up to request clarification or add additional context in comments.

1 Comment

This is really clean, very nice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.