leon yin
leon yin

Reputation: 849

Concatenating dictionaries with different keys into Pandas dataframe

Let's say I have two dictionaries with shared and unshared keys:

d1 = {'a': 1, 'b': 2}
d2 = {'b': 4, 'c': 3}

How would I concatenate them into a dataframe that's akin to one-hot enoding?

a   b   c
1   2   
    4   3

Upvotes: 1

Views: 1577

Answers (1)

piRSquared
piRSquared

Reputation: 294318

If you want the same result as what you are showing...

pd.DataFrame([d1, d2], dtype=object).fillna('')

   a  b  c
0  1  2   
1     4  3

If you want to fill missing values with zero and keep a int dtype...

pd.concat(dict(enumerate(map(pd.Series, [d1, d2])))).unstack(fill_value=0)

   a  b  c
0  1  2  0
1  0  4  3

Or as pointed out by OP in comments

pd.DataFrame([d1, d2], dtype=object).fillna(0).astype(int)

   a  b  c
0  1  2  0
1  0  4  3

Upvotes: 2

Related Questions