【问题标题】:union of two dataframes' index and columns两个数据框的索引和列的联合
【发布时间】:2018-03-03 23:52:11
【问题描述】:

我不确定它是否是正确的表达式,但是搜索合并或更改索引并没有让我找到任何地方。基本上我有两个数据框:

df_A = pd.DataFrame(1, index=[1,2,3], columns = [1,2,3])
df_B = pd.DataFrame(0, index=[1,2,4], columns = [1,2,5])

我想转换 df_A 和 df_B 以便它们共享相同的索引和列,它们是两者的联合。缺失值将用 NaN 填充:

df_A_new:
          1    2    3    5
index
1         1    1    1   NaN
2         1    1    1   NaN
3         1    1    1   NaN
4        NaN  NaN  NaN  NaN

df_B_new:
          1    2    3    5
index
1         0    0   NaN   0
2         0    0   NaN   0
3        NaN  NaN  NaN  NaN
4         0    0   NaN   0

【问题讨论】:

    标签: python pandas indexing union


    【解决方案1】:

    您可以使用.union.reindex

    rows = df_A.index.union(df_B.index)
    cols = df_A.columns.union(df_B.columns)
    
    df_A_new = df_A.reindex(index=rows, columns=cols)
    df_B_new = df_B.reindex(index=rows, columns=cols)
    

    df_A_new 看起来像

         1    2    3   5
    1  1.0  1.0  1.0 NaN
    2  1.0  1.0  1.0 NaN
    3  1.0  1.0  1.0 NaN
    4  NaN  NaN  NaN NaN
    

    df_B_new 看起来像:

         1    2   3    5
    1  0.0  0.0 NaN  0.0
    2  0.0  0.0 NaN  0.0
    3  NaN  NaN NaN  NaN
    4  0.0  0.0 NaN  0.0
    

    【讨论】:

    • 谢谢!正是我要找的!显然我不能在 10 分钟内接受答案......所以到那时我会点击你的答案
    猜你喜欢
    • 2015-10-28
    • 1970-01-01
    • 2021-04-21
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多