8

How to create a pandas DataFrame out of two and more dictionaries having common keys? That is, to convert

d1 = {'a': 1}
d2 = {'a': 3}
...

into a dataframe with columns ['d1', 'd2', ...], rows indexed like "a" and values determined by the respective dictionaries?

Anton Tarasenko
  • 8,099
  • 11
  • 66
  • 91
  • this question have been asked here : http://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string – Colonel Beauvel Sep 12 '14 at 17:55
  • @ColonelBeauvel eh, I think only if you squint, unless you linked the wrong question by accident – Ajean Sep 12 '14 at 19:26
  • @Ajean Dictionnaries could have been named d45, d34, .. etc with some random numbers. In that case the answer below does not work. The author in the link underlines this tricky point: "I would like to create a DataFrame in Pandas from this list, where the column names are given by the names of the actual dictionaries" – Colonel Beauvel Sep 12 '14 at 19:29
  • @ColonelBeauvel Sorry, I should have been more clear - I really meant that that question is posed completely differently: the same true underlying question has been *answered* there (I think) but not really *asked* (until you read way down) – Ajean Sep 12 '14 at 19:38

1 Answers1

9
import pandas as pd
d1 = {'a': 1, 'b':2}
d2 = {'a': 3, 'b':5}

df = pd.DataFrame([d1, d2]).T
df.columns = ['d{}'.format(i) for i, col in enumerate(df, 1)]

yields

In [40]: df
Out[40]: 
   d1  d2
a   1   3
b   2   5
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677