Guforu
Guforu

Reputation: 4023

DataFrame from dictionary

Sorry, if it is a duplicate, but I didn't find the solution in internet...

I have some dictionary

{'a':1, 'b':2, 'c':3}

Now I want to construct pandas DF with the columns names corresponding to key and values corresponding to values. Actually it should be Df with only one row.

a b c
1 2 3

At the other topic I found only solutions, where both - keys and values are columns in the new DF.

Upvotes: 2

Views: 6301

Answers (2)

jpp
jpp

Reputation: 164823

For flexibility, you can also use pd.DataFrame.from_dict with orient='index'. This works whether your dictionary values are scalars or lists.

Note the final transpose step, which can be performed via df.T or df.transpose().

temp1 = {'a': 1, 'b': 2, 'c': 3}
temp2 = {'a': [1, 2], 'b':[2, 3], 'c':[3, 4]}

print(pd.DataFrame.from_dict(temp1, orient='index').T)

   a  b  c
0  1  2  3

print(pd.DataFrame.from_dict(temp2, orient='index').T)

   a  b  c
0  1  2  3
1  2  3  4

Upvotes: 1

EdChum
EdChum

Reputation: 394419

You have some caveats here, if you just pass the dict to the DataFrame constructor then it will raise an error:

ValueError: If using all scalar values, you must must pass an index

To get around that you can pass an index which will work:

In [139]:

temp = {'a':1,'b':2,'c':3}
pd.DataFrame(temp, index=[0])
Out[139]:
   a  b  c
0  1  2  3

Ideally your values should be iterable, so a list or array like:

In [141]:

temp = {'a':[1],'b':[2],'c':[3]}
pd.DataFrame(temp)
Out[141]:
   a  b  c
0  1  2  3

Thanks to @joris for pointing out that if you wrap the dict in a list then you don't have to pass an index to the constructor:

In [142]:

temp = {'a':1,'b':2,'c':3}
pd.DataFrame([temp])
Out[142]:
   a  b  c
0  1  2  3

Upvotes: 7

Related Questions