行上应用的几何均值 [英] Geometric mean applied on row
本文介绍了行上应用的几何均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我以这个数据框为例:
Col1 Col2 Col3 Col4
1 2 3 2.2
我想添加一个名为"Gmean"的第4列,该列计算每行的前3列的几何平均值.
I would like to to add a 4th column called 'Gmean' that calculate the geometric mean of the first 3 columns on each row.
如何完成它?
谢谢!
推荐答案
One way would be with Scipy's geometric mean function
-
from scipy.stats.mstats import gmean
df['Gmean'] = gmean(df.iloc[:,:3],axis=1)
formula of geometric mean
本身的另一种方式-
Another way with the formula of geometric mean
itself -
df['Gmean'] = np.power(df.iloc[:,:3].prod(axis=1),1.0/3)
如果正好有3
列,则只需使用df
而不是df.iloc[:,:3]
.另外,如果您正在寻找性能,则可能要使用df.values
或df.iloc[:,:3].values
处理基础数组数据.
If there are exactly 3
columns, just use df
instead of df.iloc[:,:3]
. Also, if you are looking for performance, you might want to work with the underlying array data with df.values
or df.iloc[:,:3].values
.
这篇关于行上应用的几何均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文