Geoffrey Negiar
Geoffrey Negiar

Reputation: 849

Dictionary of Pandas Dataframes to MultiIndex Dataframe

I have a dict of Pandas Dataframes, say

d = {A: pd.DataFrame([[0, 1, 2], [2, 2, 4]),
     B: pd.DataFrame([[1, 1, 1], [2, 2, 2]}

and I'd like to change it into a MultiIndex DataFrame like this:

A 0   0, 1, 2
  1   2, 2, 4
B 0   1, 1, 1
  1   2, 2, 2

Upvotes: 23

Views: 8653

Answers (1)

root
root

Reputation: 33793

Use pd.concat on the dictionary values, with the keys parameter set to the dictionary keys:

df = pd.concat(d.values(), keys=d.keys())

The resulting output:

     0  1  2
A 0  0  1  2
  1  2  2  4
B 0  1  1  1
  1  2  2  2

Upvotes: 31

Related Questions