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

如何用Python在Pandas DataFrame生成满足条件的重置累计列?

解决方案

针对你需要为超大规模Pandas DataFrame(3000万行)生成符合规则的累计列需求,推荐使用全矢量化的Pandas内置操作,避免低效的apply逐行处理,具体实现步骤如下:

核心思路

通过标记重置分界点,将连续符合条件的行划分为分组,再在分组内计算累计计数,最后将非0值行的计数重置为0。

代码实现

import pandas as pd

# 假设你的DataFrame名为df
# 1. 生成重置标记:当用户变更或Value Col不为0时标记为True
df['flag'] = (df['User'] != df['User'].shift()) | (df['Value Col'] != 0)

# 2. 生成分组编号:每次遇到重置标记,分组号递增
df['group_num'] = df['flag'].cumsum()

# 3. 计算组内累计计数,再将非0值行的计数设为0
df['Running total'] = df.groupby('group_num').cumcount() + 1
df.loc[df['Value Col'] != 0, 'Running total'] = 0

# 可选:删除中间辅助列
df = df.drop(['flag', 'group_num'], axis=1)

效果验证

以上代码完全匹配你给出的示例输出:

  • 当用户不变且Value Col为0时,累计数逐行递增
  • 用户变更或Value Col不为0时,累计数重置为0
  • 新用户的第一个0值行,累计数从1开始

备选方案(不推荐用于大数据集)

若因特殊规则必须使用apply,可按用户分组后逐行计算,但该方法处理3000万行速度极慢:

def calc_running_total(group):
    total = 0
    result = []
    for val in group['Value Col']:
        total = total + 1 if val == 0 else 0
        result.append(total)
    return result

df['Running total'] = df.groupby('User')['Value Col'].apply(calc_running_total).explode()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 09:06:05