【发布时间】:2017-05-17 20:53:26
【问题描述】:
假设我有两个带有共享和非共享键的字典:
d1 = {'a': 1, 'b': 2}
d2 = {'b': 4, 'c': 3}
我如何将它们连接成类似于 one-hot enoding 的数据帧?
a b c
1 2
4 3
【问题讨论】:
标签: python pandas dictionary one-hot-encoding
假设我有两个带有共享和非共享键的字典:
d1 = {'a': 1, 'b': 2}
d2 = {'b': 4, 'c': 3}
我如何将它们连接成类似于 one-hot enoding 的数据帧?
a b c
1 2
4 3
【问题讨论】:
标签: python pandas dictionary one-hot-encoding
如果你想要和你展示的一样的结果......
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 在 cmets 中指出的那样
pd.DataFrame([d1, d2], dtype=object).fillna(0).astype(int)
a b c
0 1 2 0
1 0 4 3
【讨论】:
astype(int)... pd.DataFrame([d1, d2], dtype=object).fillna(0).astype(int)