【问题标题】:How to sum each row and replace each value in row with sum?如何对每一行求和并用总和替换行中的每个值?
【发布时间】:2019-06-14 06:38:10
【问题描述】:

如果我有这样的数据框:

   1  2  3  4  5
 1 2  4  5 NaN 3
 2 3  5  6  1  2
 3 3  1  1  1  1

如何对每一行求和并用总和替换该行中的值,以便得到如下结果:

   1   2  3  4  5
 1 14 14 14 NaN 14
 2 17 17 17 17  17
 3 7  7  7  7   7

【问题讨论】:

    标签: python pandas python-2.7 dataframe


    【解决方案1】:

    使用mask 将所有非缺失值替换为sum

    df = df.mask(df.notnull(), df.sum(axis=1), axis=0)
    print (df)
        1   2   3     4   5
    1  14  14  14   NaN  14
    2  17  17  17  17.0  17
    3   7   7   7   7.0   7
    

    或将numpy.broadcast_tonumpy.where 一起使用:

    arr = df.values
    a = np.broadcast_to(np.nansum(arr, axis=1)[:, None], df.shape)
    df = pd.DataFrame(np.where(np.isnan(arr), np.nan, a),
                      index=df.index, columns=df.columns)
    
    #alternative
    df[:] = np.where(np.isnan(arr), np.nan, a)
    print (df)
          1     2     3     4     5
    1  14.0  14.0  14.0   NaN  14.0
    2  17.0  17.0  17.0  17.0  17.0
    3   7.0   7.0   7.0   7.0   7.0
    

    【讨论】:

      【解决方案2】:

      使用mul

      df.notnull().replace(False,np.nan).mul(df.sum(1),axis=0).astype(float)
            1     2     3     4     5
      1  14.0  14.0  14.0   NaN  14.0
      2  17.0  17.0  17.0  17.0  17.0
      3   7.0   7.0   7.0   7.0   7.0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        • 1970-01-01
        • 2021-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多