Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested dictionary to dataframe preserving the dictionary key as column instead of index

The dictionary is of format as shown

{1:{'3450':0.235, '4380':0.47823},11:{'0430':0.128912,'0986':0.6267},14:{'8060':0.218912,'1234':0.6238}}

Can I create a dataframe as shown

   chapter name  value
 0    1    3450  0.235
 1    1    4380  0.478
 2    11   0430  0.128912
 3    11   0986  0.6267
 4    14   8060  0.218912
 5    14   1234  0.6238

I tried converting to dataframe, But I get the chapter as index, I need that as a column.

like image 820
Vamsi Nimmala Avatar asked Dec 17 '25 17:12

Vamsi Nimmala


2 Answers

Using stack

df=pd.DataFrame(d).stack().reset_index()
df.columns=['name','chapter','value']
df
Out[113]: 
   name  chapter     value
0  0430       11  0.128912
1  0986       11  0.626700
2  1234       14  0.623800
3  3450        1  0.235000
4  4380        1  0.478230
5  8060       14  0.218912
like image 50
BENY Avatar answered Dec 20 '25 08:12

BENY


Or manually:

df=pd.DataFrame(d).reset_index()
df['value']=df.pop(1).fillna(df.pop(11)).fillna(df.pop(14))
df['chapter']=sorted(list(d.keys())*2)
df.columns=['name','value','chapter']

Then now:

print(df)

Is:

   name     value  chapter
0  0430  0.128912        1
1  0986  0.626700        1
2  1234  0.623800       11
3  3450  0.235000       11
4  4380  0.478230       14
5  8060  0.218912       14

To reorder columns:

df=df[['chapter','name','value']]
like image 21
U12-Forward Avatar answered Dec 20 '25 08:12

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!