You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas如何按另一列权重计算指定列的分组加权平均分

pandas按分组计算指定列加权平均分的实现方法

加权平均分的计算逻辑为:分组内(权重列 * 目标计算列)的求和值 / 权重列的求和值,你可以直接借助pandas的groupby能力实现,以下是完整可运行的代码:

import pandas as pd

# 构造示例数据
df = pd.DataFrame([['A',10,2],['A',15,4],['A',20,6],['B',5,5],['B',10,8]],columns = ['Group', '#items', 'score'])

# 方法1:自定义函数实现,可读性更强
def cal_weighted_avg(group, weight_col='#items', target_col='score'):
    weighted_sum = (group[target_col] * group[weight_col]).sum()
    weight_total = group[weight_col].sum()
    return round(weighted_sum / weight_total, 3)

result = df.groupby('Group').apply(cal_weighted_avg).reset_index(name='avg_weighted_score')

# 方法2:大数据量场景下性能更优的写法,避免逐组apply循环
df['tmp_weighted_score'] = df['score'] * df['#items']
group_df = df.groupby('Group').agg(
    total_weight=('#items', 'sum'),
    total_weighted_score=('tmp_weighted_score', 'sum')
)
group_df['avg_weighted_score'] = round(group_df['total_weighted_score']/group_df['total_weight'], 3)
result = group_df[['avg_weighted_score']].reset_index()

输出的result结果完全符合预期:

Group  avg_weighted_score
0     A               4.444
1     B               7.000

内容的提问来源于stack exchange,提问作者Javier Monsalve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:06:03