一行代码计算加权平均值

问题描述 投票:0回答:1

我想用一行或几行代码计算加权平均值

我不想为每一列写单独的代码

列值将是我的权重

这是我的数据框:

df2 = pd.DataFrame({'class': ['Falcon', 'Falcon', 'Parrot', 'Parrot'],
                    'V1': [380., 370., 248., 269.],
                    'V2' : [263, 542, 456, 531],
                    'V3': [0, 0, 356, 541],
                    'price':[3, 5, 1, 5]});

var_cols = ['V1', 'V2', 'V3'] ;

df2.groupby('class').apply(lambda x: 0 if (sum(x[v] == 0)) else pd.Series([sum(x[v] * x.price) / sum(x[v]) for v in var_cols]));

在我的例子中,重量是 V1、V2 和 V3

python if-statement lambda list-comprehension apply
1个回答
0
投票

您可以使用以下内容

df.groupby('class') \
   .apply(
    lambda frame: \
        frame[['V1', 'V2', 'V3']].multiply(frame['price'], axis='index').sum(axis=0) \
            .multiply(1/frame[['V1', 'V2', 'V3']].sum(axis=0))) \
  .reset_index(drop=False) \
  .rename({'V1': 'price_weighted_average_v1', 'V2': 'price_weighted_average_v2', 'V3': 'price_weighted_average_v3'}, axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.