1

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
leon yin
  • 829
  • 3
  • 10
  • 23

1 Answers1

2

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
piRSquared
  • 285,575
  • 57
  • 475
  • 624