如何按ID及指定起始日期回溯两年对points变量求和?
按ID计算指定日期前两年的Points总和
原始数据示例
| ID | date | points |
|---|---|---|
| 1 | 2010-05-10 | 10 |
| 1 | 2011-12-20 | 20 |
| 1 | 2012-03-05 | 15 |
| 2 | 2011-01-15 | 5 |
| 2 | 2012-11-30 | 25 |
| 2 | 2013-02-10 | 30 |
需求说明
针对每个ID,分别计算两个时间范围内的points总和:
- 范围1:从
2010-01-01到2012-01-01(以2012-01-01为终点,往前推两年) - 范围2:从
2011-01-01到2013-01-01(以2013-01-01为终点,往前推两年)
实现方案(Python Pandas)
以下是基于Pandas的代码实现,可直接适配你的数据集:
import pandas as pd # 加载数据集(替换为你的实际数据路径或数据源) df = pd.DataFrame({ 'ID': [1,1,1,2,2,2], 'date': ['2010-05-10','2011-12-20','2012-03-05','2011-01-15','2012-11-30','2013-02-10'], 'points': [10,20,15,5,25,30] }) # 将date字段转换为datetime格式,便于时间筛选 df['date'] = pd.to_datetime(df['date']) # 定义需要计算的两个目标终点日期 target_dates = pd.to_datetime(['2012-01-01', '2013-01-01']) # 存储每个目标日期的计算结果 result_list = [] for target_date in target_dates: # 计算当前目标日期往前推两年的起始日期 start_date = target_date - pd.DateOffset(years=2) # 筛选出ID对应的日期范围内的数据 filtered_data = df[(df['date'] >= start_date) & (df['date'] <= target_date)] # 按ID分组求和points sum_result = filtered_data.groupby('ID')['points'].sum().reset_index() # 添加辅助字段,明确计算的时间范围和目标日期 sum_result['target_date'] = target_date.strftime('%Y-%m-%d') sum_result['date_range'] = f"{start_date.strftime('%Y-%m-%d')}至{target_date.strftime('%Y-%m-%d')}" result_list.append(sum_result) # 合并所有结果并输出 final_result = pd.concat(result_list, ignore_index=True) print(final_result)
预期输出示例
| ID | points | target_date | date_range |
|---|---|---|---|
| 1 | 30 | 2012-01-01 | 2010-01-01至2012-01-01 |
| 2 | 5 | 2012-01-01 | 2010-01-01至2012-01-01 |
| 1 | 35 | 2013-01-01 | 2011-01-01至2013-01-01 |
| 2 | 30 | 2013-01-01 | 2011-01-01至2013-01-01 |
内容的提问来源于stack exchange,提问作者Nona
相关产品推荐
相关产品推荐

