Skip to content

Instantly share code, notes, and snippets.

@bruno-uy
Created June 4, 2021 18:56
Show Gist options
  • Save bruno-uy/66e539c2b119b31f8e4ec4d09118af89 to your computer and use it in GitHub Desktop.
Save bruno-uy/66e539c2b119b31f8e4ec4d09118af89 to your computer and use it in GitHub Desktop.
Multiindex pandas DataFrame to multi level nested dictionary
import pandas as pd
df = pd.DataFrame({"A": [0, 1, 0], "B": ["a", "b", "c"], "C": [1, 2, 3]})
df.set_index(["A", "C"], drop=False, inplace=True)
result = {level: df.xs(level).to_dict("index") for level in df.index.levels[0]}
print(result[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment