【问题标题】:Concatenating dictionaries with different keys into Pandas dataframe将具有不同键的字典连接到 Pandas 数据框中
【发布时间】: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


    【解决方案1】:

    如果你想要和你展示的一样的结果......

    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
    

    【讨论】:

    • 谢谢!这不适合ex2吗? pd.DataFrame([d1, d2], dtype=object).fillna(0)
    • @leonyin 是的,但我会添加 astype(int)... pd.DataFrame([d1, d2], dtype=object).fillna(0).astype(int)
    猜你喜欢
    • 1970-01-01
    • 2018-08-06
    • 2017-05-02
    • 2023-02-21
    • 2016-07-21
    • 2022-12-10
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多