Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining same-key dictionaries into a dataframe in pandas

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?

like image 920
Anton Tarasenko Avatar asked Sep 12 '14 17:09

Anton Tarasenko


People also ask

How do I merge two dictionaries in pandas?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries.

How do I turn a list of dictionaries into a Pandas DataFrame?

Use pd. DataFrame. from_dict() to transform a list of dictionaries to pandas DatFrame. This function is used to construct DataFrame from dict of array-like or dicts.


1 Answers

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
like image 187
unutbu Avatar answered Oct 20 '22 07:10

unutbu