Pandas 加权平均

Pandas 加权平均,pandas,Pandas,我正在使用熊猫计算许多列的加权平均值。在某些情况下,重量之和可能为零,因此我使用np.ma.average: import pandas as pd import numpy as np df = pd.DataFrame.from_dict(dict([('ID', [1, 1, 1]),('HeightA', [1, 2, 3]), ('WeightA', [0, 0, 0]),('HeightB', [2, 4, 6]), ('WeightB', [1, 2, 4])])) >&

我正在使用熊猫计算许多列的加权平均值。在某些情况下,重量之和可能为零,因此我使用np.ma.average:

import pandas as pd
import numpy as np

df = pd.DataFrame.from_dict(dict([('ID', [1, 1, 1]),('HeightA', [1, 2, 3]), ('WeightA', [0, 0, 0]),('HeightB', [2, 4, 6]), ('WeightB', [1, 2, 4])]))

>>df
   ID  HeightA  WeightA  HeightB  WeightB
0   1        1        0        2        1
1   1        2        0        4        2
2   1        3        0        6        4


wmA = lambda x: np.ma.average(x, weights=df.loc[x.index, "WeightA"])
wmB = lambda x: np.ma.average(x, weights=df.loc[x.index, "WeightB"])
f = {'HeightA':wmA,'HeightB':wmB}
df2 = df.groupby(['ID'])['HeightA','HeightB'].agg(f)
这是可行的,但我有很多列的高度和重量,所以我不想为每一列编写lambda函数,所以我尝试:

def givewm(data,weightcolumn):
    return np.ma.average(data, weights=data.loc[data.index, weightcolumn])

f = {'HeightA':givewm(df,'WeightA'),'HeightB':givewm(df,'WeightB')}
df2 = df.groupby(['ID'])['HeightA','HeightB'].agg(f)
当a的形状和权重不同时,必须指定哪个轴提供错误:builtins.TypeError:Axis


如何编写一个返回加权平均值并将加权列名作为输入的函数?

使用双嵌套函数,解决方案来自:

验证解决方案:

wmA = lambda x: np.ma.average(x, weights=df.loc[x.index, "WeightA"])
wmB = lambda x: np.ma.average(x, weights=df.loc[x.index, "WeightB"])
f = {'HeightA':wmA,'HeightB':wmB}

df2 = df.groupby(['ID'])['HeightA','HeightB'].agg(f)
print (df2)
     HeightA   HeightB
ID                    
1   2.333333  4.857143
wmA = lambda x: np.ma.average(x, weights=df.loc[x.index, "WeightA"])
wmB = lambda x: np.ma.average(x, weights=df.loc[x.index, "WeightB"])
f = {'HeightA':wmA,'HeightB':wmB}

df2 = df.groupby(['ID'])['HeightA','HeightB'].agg(f)
print (df2)
     HeightA   HeightB
ID                    
1   2.333333  4.857143