【问题标题】:Geometric mean applied on row应用于行的几何平均值
【发布时间】:2017-07-15 03:55:51
【问题描述】:

我以这个数据框为例:

Col1       Col2       Col3       Col4
   1          2          3        2.2

我想添加一个名为“Gmean”的第 4 列,用于计算每行前 3 列的几何平均值。

怎样才能做到?

谢谢!

【问题讨论】:

    标签: python pandas numpy scipy


    【解决方案1】:
    df.assign(Gmean=df.iloc[:, :3].prod(1) ** (1. / 3))
    
       Col1  Col2  Col3  Col4     Gmean
    0     1     2     3   2.2  1.817121
    

    【讨论】:

      【解决方案2】:

      一种方法是使用Scipy's geometric mean function -

      from scipy.stats.mstats import gmean
      
      df['Gmean'] = gmean(df.iloc[:,:3],axis=1)
      

      formula of geometric mean 本身的另一种方式 -

      df['Gmean'] = np.power(df.iloc[:,:3].prod(axis=1),1.0/3)
      

      如果正好有 3 列,只需使用 df 而不是 df.iloc[:,:3]。此外,如果您正在寻找性能,您可能希望使用 df.valuesdf.iloc[:,:3].values 处理底层数组数据。

      【讨论】:

        猜你喜欢
        • 2014-08-17
        • 2021-11-29
        • 2020-03-07
        • 2020-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-05
        • 1970-01-01
        相关资源
        最近更新 更多