Converting a nested python dictionary into a multi-indexed pandas dataframe -
how convert nested dictionary pandas multi-indexed dataframe?
here example:
dct={'outer':{}} in dct: dct[i]={'middle':{}} j in dct[i]: dct[i][j]={} j in dct[i]: dct[i][j]['inner']=10 print dct
which outputs:
{'outer': {'middle': {'inner': 10}}}
i want in pandas dataframe looks this:
outer middle inner value inner2 value middle2 inner value outer2 middle inner value inner2 value middle2 inner value
i'm aware multi-indexing way i'm not sure how make data frame. can give me pointers?
i think can use concat
created dict comprehension
dataframe.from_dict
, last stack
- output series
multiindex
:
dct={'outer':{}, 'outer2':{}} in dct: dct[i]={'middle':{}, 'middle2':{}} j in dct[i]: dct[i][j]={} j in dct[i]: dct[i][j]['inner']=10 dct[i][j]['inner2']=20 print (dct) {'outer2': {'middle2': {'inner': 10, 'inner2': 20}, 'middle': {'inner': 10, 'inner2': 20}}, 'outer': {'middle2': {'inner': 10, 'inner2': 20}, 'middle': {'inner': 10, 'inner2': 20}}}
print (pd.concat({key:pd.dataframe.from_dict(dct[key],orient='index') key in dct.keys()})) inner inner2 outer middle 10 20 middle2 10 20 outer2 middle 10 20 middle2 10 20 df = pd.concat({key:pd.dataframe.from_dict(dct[key], orient='index') key in dct.keys()}).stack() print (df) outer middle inner 10 inner2 20 middle2 inner 10 inner2 20 outer2 middle inner 10 inner2 20 middle2 inner 10 inner2 20 dtype: int64
Comments
Post a Comment