将具有不同键的字典连接到Pandas数据框 [英] Concatenating dictionaries with different keys into Pandas dataframe
本文介绍了将具有不同键的字典连接到Pandas数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两个带有共享和非共享密钥的字典:
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
推荐答案
如果您希望获得与显示的结果相同的结果...
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
如果要用零填充缺失值并保持int
dtype
...
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
或者正如OP在评论中指出的那样
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
这篇关于将具有不同键的字典连接到Pandas数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文