Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep dictionary key as first column when transformed into dataframe?

I'd like to transform dictionary into dataframe.

dic={'a': [5, 9],
     'b': [4, 61],
     'c': [24, 9]}

If you do:

df=pd.DataFrame(dic).transpose()

You'll have:

    0   1
a   5   9
b   4  61
c  24   9

But I'd like to keep the dictionary key as the first column,how could I do?

name   F0   F1
a      5    9
b      4    61
c      24   9
like image 747
LookIntoEast Avatar asked Nov 08 '25 10:11

LookIntoEast


1 Answers

I think simpliest is reset_index:

df=pd.DataFrame(dic, index=['F0','F1']).rename_axis('name', axis=1).transpose().reset_index()
print (df)
  name  F0  F1
0    a   5   9
1    b   4  61
2    c  24   9

And also:

df=pd.DataFrame.from_dict(dic, orient='index').reset_index()
df.columns = ['name','F0','F1']
print (df)
  name  F0  F1
0    b   4  61
1    c  24   9
2    a   5   9

Another a bit hack - add value from key to values in dict comprehension, but also reset_index is necessary for default monotonic index (0,1,2..):

dic = {k:[k]+v for k,v in dic.items()}
print (dic)
{'b': ['b', 4, 61], 'c': ['c', 24, 9], 'a': ['a', 5, 9]}

df=pd.DataFrame(dic, index=['name','F0','F1']).transpose().reset_index(drop=True)
print (df)

  name  F0  F1
0    a   5   9
1    b   4  61
2    c  24   9
like image 98
jezrael Avatar answered Nov 10 '25 00:11

jezrael



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!