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

Pandas按客户分组:仅当Timestamp<Timestamp2时计算Dollar Value累计和

用GroupBy + Apply实现客户级条件累计求和

嘿,这个需求完全可以通过groupby配合自定义函数来实现,不用折腾笛卡尔连接或者逐行遍历,代码简洁高效。咱们一步步来:

1. 准备数据和排序

先把你给出的DataFrame和排序步骤用代码落地:

import pandas as pd

# 原始数据
df = pd.DataFrame({
    'Customer': ['Alice','Brian','Alice','Alice','Alice','Brian', 'Brian'],
    'Timestamp': [1,2,3,4,5,3,6],
    'Timestamp 2': [2,5,4,6,7,5,7],
    'Dollar Value': [0,1,3,5,3,2,3]
})

# 按客户和Timestamp排序,保证同客户的数据按时间顺序排列
df = df.sort_values(['Customer','Timestamp']).reset_index(drop=True)

2. 核心实现:GroupBy + 自定义函数

根据你给出的预期结果,这里的逻辑应该是:对每个客户的每一行,计算该客户中所有满足「Timestamp小于当前行Timestamp2,且Timestamp2小于当前行Timestamp」的行的Dollar Value总和。用groupby('Customer').apply()就能轻松实现:

def calculate_desired_result(group):
    result = []
    # 遍历组内的每一行,计算符合条件的求和
    for idx, current_row in group.iterrows():
        # 筛选同客户中满足双条件的行
        match_mask = (group['Timestamp'] < current_row['Timestamp 2']) & (group['Timestamp 2'] < current_row['Timestamp'])
        # 对筛选后的Dollar Value求和
        total = group.loc[match_mask, 'Dollar Value'].sum()
        result.append(total)
    # 将结果赋值给新列
    group['Desired_result'] = result
    return group

# 把函数应用到每个客户分组,group_keys=False避免生成多余的分组索引
df = df.groupby('Customer', group_keys=False).apply(calculate_desired_result)

3. 验证结果

运行代码后,你会得到和预期完全一致的输出:

print(df)

输出内容:

Customer  Timestamp  Timestamp 2  Dollar Value  Desired_result
0    Alice           1            2             0               0
1    Alice           3            4             3               0
2    Alice           4            6             5               0
3    Alice           5            7             3               3
4    Brian           2            5             1               0
5    Brian           3            5             2               0
6    Brian           6            7             3               3

补充说明

如果你的需求是更基础的「仅当当前行Timestamp < Timestamp2时,累计该行及之前满足条件的Dollar Value」,代码可以简化成这样:

def simple_cumulative_sum(group):
    # 标记满足条件的行
    group['is_valid'] = group['Timestamp'] < group['Timestamp 2']
    # 只对满足条件的行做累计求和,不满足的位置设为0
    group['Desired_result'] = group['Dollar Value'].where(group['is_valid'], 0).cumsum()
    return group

df = df.groupby('Customer', group_keys=False).apply(simple_cumulative_sum)

不过这个逻辑得到的结果和你给出的预期不符,所以我优先采用了匹配你预期的实现逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:10:41