Concatenating dictionaries with different keys into Pandas dataframe

依然范特西╮ 提交于 2019-12-24 07:58:10

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/44034600/concatenating-dictionaries-with-different-keys-into-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!