python - 将具有不同键的字典连接到 Pandas 数据框中

标签 python pandas dictionary one-hot-encoding

假设我有两个带有共享 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/

相关文章:

python - 删除 Pandas 中特定列(按名称)之前的所有列?

python - 设置 Google Adwords API 的客户 ID

Python 正则表达式 : why doesn't python accept my pattern?

Python 精度处理

python - 如何在Python中比较两个不同.csv文件中的列?

python - 为什么我在 pandas 的 apply/assign 函数中得到一个系列?想要使用每个值来查找字典

python - 规范化 Gensim 中的词袋数据

javascript - 如何打印字典字典的内容?

python - 在 Python 中,如何轻松地从字典中检索已排序的项目?

.net - 为什么 .NET 中没有 XML 可序列化字典?