Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating data frame from dictionary where row names is key of the dictionary in Pandas

Tags:

python

pandas

I have dictionary that looks like this:

In [1]: import pandas as pd 
In [2]: mydict = {'foo':0.3, 'bar':0.55}

What I want to to do is to create a data frame that looks like this:

bar 0.55
foo 0.3

What's the right way to do it? I tried this

In [5]: pd.DataFrame(mydict, index=[0])
Out[5]: 
    bar  foo
0  0.55  0.3

Note that we literally wanted to use 'DataFrame' not 'Series', because later we need to merge them.

like image 410
pdubois Avatar asked Jan 07 '15 04:01

pdubois


2 Answers

The recommended method is to use from_dict which is preferable to transposing after creation IMO:

In [21]:

df = pd.DataFrame.from_dict(mydict, orient='index')
df
Out[21]:
        0
bar  0.55
foo  0.30
like image 131
EdChum Avatar answered Nov 15 '22 11:11

EdChum


Just transpose it after you've created the DataFrame:

In [1]: import pandas as pd 
In [2]: mydict = {'foo':0.3, 'bar':0.55}
In [3]: pd.DataFrame(mydict).T
like image 28
MTrenfield Avatar answered Nov 15 '22 13:11

MTrenfield