Skip to content

Instantly share code, notes, and snippets.

@dcragusa
Last active September 19, 2024 04:48
Show Gist options
  • Save dcragusa/1235704accde2152faa37113cafa95c0 to your computer and use it in GitHub Desktop.
Save dcragusa/1235704accde2152faa37113cafa95c0 to your computer and use it in GitHub Desktop.
Converts a MultiIndexed Dataframe to a nested dict - this was used in a Django template
import pandas as pd
from collections import OrderedDict
from pandas.core.indexes.multi import MultiIndex
def multiindex_to_nested_dict(df: pd.DataFrame, value_only = False) -> OrderedDict:
if isinstance(df.index, MultiIndex):
return OrderedDict((k, multiindex_to_nested_dict(df.loc[k])) for k in df.index.remove_unused_levels().levels[0])
else:
if value_only:
return OrderedDict((k, df.loc[k].values[0]) for k in df.index)
else:
d = OrderedDict()
for idx in df.index:
d_col = OrderedDict()
for col in df.columns:
d_col[col] = df.loc[idx, col]
d[idx] = d_col
return d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment