#๐Ÿ”’ How to convert a nested dictionary into a nested dataframe using Pandas

4 messages ยท Page 1 of 1 (latest)

slender coral
#

I put up a post on SO to convert a nested dataframe into Pandas. However, I don't understand the answer very well.

Here is my data -

nested_dict = {
    'Marks': {
        'Physics': {
            'Theo': 99,
            'Prac': 100
        },
        'Biology': {
            'Theo': 89,
            'Prac': 100
        }
    }
}

I want the output in this way -


           Marks
  Physics   |      Biology
 Theo|Prac  |     Theo|Prac
  99 | 100  |      89 | 100 

Someone answered with the following code -

out = (pd.concat({k: pd.DataFrame(v)
                  for k, v in nested_dict.items()},
                 axis=1)
         .unstack().to_frame().T
      )

Here is what I understood -

for k, v in nested_dict.items() We are iterating through the dictionary with k as keys and v as values. But everything else seems confusing

steep spearBOT
#

@slender coral

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

steep spearBOT
#

@slender coral

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.