Skip to content
Advertisement

Convert pandas DataFrame to a nested dict

I’m Looking for a generic way of turning a DataFrame to a nested dictionary

This is a sample data frame

JavaScript

The number of columns may differ and so does the column names.

like this :

JavaScript

What is best way to achieve this ?

closest I got was with the zip function but haven’t managed to make it work for more then one level (two columns).

Advertisement

Answer

I don’t understand why there isn’t a B2 in your dict. I’m also not sure what you want to happen in the case of repeated column values (every one except the last, I mean.) Assuming the first is an oversight, we could use recursion:

JavaScript

which produces

JavaScript

It might be simpler to use a non-pandas approach, though:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement