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?
Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With