I'm trying to convert a multi-index df to a nested dictionary by aggregation sum of all index.
DataFrame is in the format
jan feb
first second third
bar bar1 bar3 0 5
bar4 4 4
bar2 bar5 1 9
foo foo1 foo3 7 2
foo4 7 7
foo2 foo5 0 3
I tried to aggregate with each index separately and convert to dict using .to_dict('records')
. But couldn't able to achieve nested dictionary with aggregation of each index
expected result is
[
{'first': 'bar',
'jan': 5,
'feb': 18,
'sub_rows': [{'second': 'bar1',
'jan': 4,
'feb': 9,
'sub_rows': [{'third': 'bar3', 'jan': 0, 'feb': 5}, {'third': 'bar4', 'jan': 4, 'feb': 4}]
},
{'second': 'bar2',
'jan': 1,
'feb': 9,
'sub_rows': [{'third': 'bar5', 'jan': 1, 'feb': 9}]
}]
},
{'first': 'foo',
'jan': 14,
'feb': 12,
'sub_rows': [{'second': 'foo1',
'jan': 14,
'feb': 9,
'sub_rows': [{'third': 'foo3', 'jan': 7, 'feb': 2}, {'third': 'foo4', 'jan': 7, 'feb': 7}]
},
{'second': 'foo2',
'jan': 0,
'feb': 3,
'sub_rows': [{'third': 'foo5', 'jan': 0, 'feb': 3}]
}]
}
]
Can you please guide me to achieve this format. Thanks