在熊猫数据框中计算加权平均值

时间:2018-07-27 14:21:39

标签: python pandas

在foll中。数据框:

                              Potential     Area       weight  
NAME                                                                    
Ket                              21.694198   61730.10  0.028773  
Chles                            31.023133  101288.07  0.047211  
Caline                           23.066401   68515.47  0.031936  
Algany                           22.794050  109111.05  0.050858  
Baire                            3.176830   20763.54  0.009678 

如何为每一列添加一个新行,其中包含该列与weight列的乘积之和?我尝试过:

df.loc['new_row'] = df.mean() * df['weight']

1 个答案:

答案 0 :(得分:1)

这是使用NumPy的一种方法:

# calculate sum of products
sums = (df.iloc[:, :2].values * df['weight'].values[:, None]).sum(0).tolist()

# assign to index label
df.loc['MeanWeightProd'] = sums + [np.nan]

print(df)

                Potential           Area    weight
NAME                                              
Ket             21.694198   61730.100000  0.028773
Chles           31.023133  101288.070000  0.047211
Caline          23.066401   68515.470000  0.031936
Algany          22.794050  109111.050000  0.050858
Baire            3.176830   20763.540000  0.009678
MeanWeightProd   4.015494   14496.300611       NaN