【问题标题】:Apend the values from one dataframe to another based on index根据索引将一个数据帧中的值附加到另一个数据帧
【发布时间】:2020-03-13 06:49:42
【问题描述】:

我有两个数据框 df1 和 df2。 df2 是 df1 的子集

df1 = df1=[[0,1,0,0],
      [1,2,0,0],
      [2,0,0,0],
      [2,4,0,0]]

df1 = pd.DataFrame(df1,columns=['A','B','C','D'])
>>> df1
   A  B  C  D
0  0  1  0  0
1  1  2  0  0
2  2  0  0  0
3  2  4  0  0

>>> df2
   C  D
2  1  3
3  2  4

我想根据索引将 C 和 D 的值从 df2 附加到 df1。

我的预期输出:

   A  B  C  D
0  0  1  0  0
1  1  2  0  0
2  2  0  1  3
3  2  4  2  4

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    使用DataFrame.update:

    注意:这是inplace,因此它会覆盖您的df1 而无需分配回

    引用自文档:

    使用来自另一个 DataFrame 的非 NA 值进行就地修改。

    在索引上对齐。没有返回值。

    df1.update(df2)
    
       A  B    C    D
    0  0  1 0.00 0.00
    1  1  2 0.00 0.00
    2  2  0 1.00 3.00
    3  2  4 2.00 4.00
    

    要转换回int,请使用DataFrame.astype

    df1 = df1.astype(int)
    
       A  B  C  D
    0  0  1  0  0
    1  1  2  0  0
    2  2  0  1  3
    3  2  4  2  4
    

    另一种不太优雅的解决方案是使用addition,然后使用fillna

    (df1 + df2).fillna(df1).astype(int)
    

    或者

    df1.add(df2).fillna(df1).astype(int)
    
       A  B  C  D
    0  0  1  0  0
    1  1  2  0  0
    2  2  0  1  3
    3  2  4  2  4
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用reindex_likefillna

      df_final = df2.reindex_like(df1).fillna(df1).astype(int)
      
      Out[89]:
         A  B  C  D
      0  0  1  0  0
      1  1  2  0  0
      2  2  0  1  3
      3  2  4  2  4
      

      【讨论】:

        猜你喜欢
        • 2019-10-14
        • 1970-01-01
        • 2020-08-20
        • 2017-04-20
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多