假设我有两个带有共享 key 和非共享 key 的字典:
d1 = {'a': 1, 'b': 2}
d2 = {'b': 4, 'c': 3}
我如何将它们连接成一个类似于one-hot enoding的数据帧?
a b c
1 2
4 3
最佳答案
如果您想要与所显示的结果相同的结果...
pd.DataFrame([d1, d2], dtype=object).fillna('')
a b c
0 1 2
1 4 3
如果您想用零填充缺失值并保留 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在评论中指出的
pd.DataFrame([d1, d2], dtype=object).fillna(0).astype(int)
a b c
0 1 2 0
1 0 4 3
关于python - 将具有不同键的字典连接到 Pandas 数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44034600/