Pandas multi index dataframe to nested dictionary
Solution 1:
You can use a dictionary comprehension to iterate through the outer levels (values 'A' and 'B') and use the xs
method to slice the frame by those levels.
{level: df.xs(level).to_dict('index') for level in df.index.levels[0]}
{'A': {'a': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
'b': {0: 6, 1: 7, 2: 8, 3: 9, 4: 1}},
'B': {'a': {0: 2, 1: 3, 2: 4, 3: 5, 4: 6},
'b': {0: 7, 1: 8, 2: 9, 3: 1, 4: 2}}}
Solution 2:
For n levels you could have something recursive like this:
def createDictFromPandas(df):
if (df.index.nlevels==1):
return df.to_dict()
dict_f = {}
for level in df.index.levels[0]:
if (level in df.index):
dict_f[level] = createDictFromPandas(df.xs([level]))
return dict_f