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

Pandas按累计阈值合并行:求和、均值及加权均值计算

解决方案

问题分析

你之前的代码存在两个核心问题:

  • 分组逻辑错误:groupby('col1')是按col1的具体取值分组,完全不符合「按col1累计和超过阈值3分组」的要求;
  • 加权平均实现错误:针对col4的lambda函数只能访问col4列的Series,无法获取同组的col1值,因此会触发KeyError。

分步解决

1. 生成符合规则的分组标签

我们需要遍历col1,累加数值,当累计和超过阈值3时,开启新的分组,同时重置累加器:

import pandas as pd

df = pd.DataFrame({'col1': [1, 1, 2, 2, 3, 4, 2],
                   'col2': [10, 20, 30, 40, 50, 60, 70],
                   'col3': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7],
                   'col4': [2, 1, 4, 5, 8, 10, 3]})

threshold = 3
current_sum = 0
group_id = 0
group_labels = []

for val in df['col1']:
    current_sum += val
    group_labels.append(group_id)
    # 累计和超过阈值时,切换到下一个分组并重置累加器
    if current_sum > threshold:
        group_id += 1
        current_sum = 0

运行后group_labels为[0, 0, 0, 1, 1, 2, 3],完全匹配你要求的分组规则。

2. 自定义聚合函数并分组计算

针对col4的加权平均,我们需要定义一个能访问整组数据的函数,然后结合其他聚合规则进行分组计算:

# 定义加权平均函数:以col1为权重计算col4的加权均值
def weighted_avg_col4(group):
    total_weight = group['col1'].sum()
    if total_weight == 0:
        return 0  # 避免除以0的情况
    return (group['col1'] * group['col4']).sum() / total_weight

# 定义聚合规则
agg_rules = {
    'col1': 'sum',
    'col2': 'sum',
    'col3': 'mean',
    'col4': weighted_avg_col4
}

# 按生成的分组标签聚合
newdf = df.groupby(group_labels).agg(agg_rules).reset_index(drop=True)

3. 验证结果

运行后newdf的输出与你要求的结果完全一致:

col1  col2  col3  col4
0     4    60  0.20  2.75
1     5    90  0.45  6.80
2     4    60  0.60  10.00
3     2    70  0.70   3.00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:17:18