23

I am familiar with python but new to panda DataFrames. I have a dictionary like this:

a={'b':100,'c':300}

And I would like to convert it to a DataFrame, where b and c are the column names, and the first row is 100,300 (100 is underneath b and 300 is underneath c). I would like a solution that can be generalized to a much longer dictionary, with many more items. Thank you!

user3433489
  • 911
  • 2
  • 10
  • 24
  • See also http://stackoverflow.com/questions/20638006/convert-list-of-dictionaries-to-dataframe/ – joris Aug 15 '14 at 07:00

3 Answers3

33

Pass the values as a list:

a={'b':[100,],'c':[300,]}
pd.DataFrame(a)

     b    c
0  100  300

Or if for some reason you don't want to use a list, include an index:

a={'b':100,'c':300}
pd.DataFrame(a, index=['i',])

     b    c
i  100  300
iayork
  • 6,420
  • 8
  • 44
  • 49
  • I have several pd.np.nan values inserted in a list of dicts.. so each element of the list is either a dict. or a nan. How would I convert it into a dataframe? – Irtaza Apr 10 '16 at 06:14
  • Not sure I understand your question. I think the approach here should work, but if not you should post this as a separate question so you can include example data – iayork Apr 11 '16 at 12:20
  • I figured it out, i changed it: now Appending a NaN filled dict i.e listt.append({"key" : pd.np.nan ....}) .. to the list.. rather than appending a pd.np.nan object directly. – Irtaza Apr 11 '16 at 13:42
0

Use lists as the values in the dictionary.

import pandas as pd
a = {'b':[100,200],'c':[300,400]}
b = pd.DataFrame(a)

In [4]: b
Out[4]: 
     b    c
0  100  300
1  200  400
Liam Foley
  • 7,432
  • 2
  • 26
  • 24
-1
loan_sanction_details = pd.DataFrame(event,index=['i',])

where loan_sanction_details is dataframe and event is dictionary.

S.B
  • 13,077
  • 10
  • 22
  • 49
Shanbhu
  • 1
  • 4
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 26 '22 at 13:40