user14384765
user14384765

Reputation: 63

Dataframe nested dictionary to multi-index dataframe

First to construct a simplified version of my question dataset, this is only helping to create a sample, I only have the final nest_dict on hand. Meaning I dont have dfs separately:

df1 = pd.DataFrame({'val':{'a': 1, 'b':2, 'c':3}})
df2 = pd.DataFrame({'val':{'a': 3, 'b':4, 'c':1}})
df3 = pd.DataFrame({'val':{'a': 2, 'b':1, 'c':4}})
dfs = [df1, df2, df3]
dates = ['2017-01-26','2017-02-03','2017-02-10']
nest_dict = {}
for date, d in zip(dates, dfs):
        nest_dict[date] = d

I would like to convert it to a Multi-Index Dataframe.

date1 a val1
      b val2
      c val3
date2 a val1
      b val2
      c val3
....

Its basically a dataframe with a date as key, it could easily become a panel, but since its been deprecated, how would I transform it to a multiindex dataframe? I did try following, but it does not work:

d = {(key, item) for key, item in corr_SH50.items()}
TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed

Upvotes: 1

Views: 61

Answers (1)

anky
anky

Reputation: 75080

concat with keys:

pd.concat(dfs,keys=dates)

              val
2017-01-26 a    1
           b    2
           c    3
2017-02-03 a    3
           b    4
           c    1
2017-02-10 a    2
           b    1
           c    4

Upvotes: 1

Related Questions