如何在Python DataFrame中实现类Excel SUMIF功能及每日阈值逻辑
问题:在Python DataFrame中实现带每日目标规则的SUMIF类功能
需求说明:
- 每日目标值为250
- 针对每个日期的序列数据,当
cum_daily_result达到250后,该日期后续所有行的expected_daily_result需固定为250 - 现有DataFrame输入列包含ID至
cum_daily_result,expected_daily_result是手动计算的预期输出
尝试的代码(未得到预期结果):
if df['cum_daily_result'][-1] >= 250: expected_daily_result = df['cum_daily_result'][-1] else: expected_daily_result = df['cum_daily_result']
解决方案
原代码的问题在于未按日期分组处理,且仅判断了整个DataFrame最后一行的数值,完全不符合“按日期追踪累积值、达到目标后固定后续值”的逻辑。以下是正确实现:
核心思路
按日期分组,对每组内的cum_daily_result序列做如下处理:
- 找到该组内第一个
cum_daily_result≥250的位置 - 从该位置开始,后续所有行的
expected_daily_result设为250 - 该位置之前的行,
expected_daily_result保留原cum_daily_result值 - 若整组未达到250,则所有行保留原累积值
代码实现
import pandas as pd # 示例DataFrame(可替换为你的实际数据) df = pd.DataFrame({ 'date': ['2024-05-01', '2024-05-01', '2024-05-01', '2024-05-02', '2024-05-02'], 'ID': [1, 2, 3, 1, 2], 'cum_daily_result': [100, 250, 300, 200, 260] }) def process_daily_target(group): # 定位首次达到目标的索引 first_reach = group[group['cum_daily_result'] >= 250].index.min() if pd.notna(first_reach): # 分割处理前后段数据 group.loc[:first_reach-1, 'expected_daily_result'] = group['cum_daily_result'] group.loc[first_reach:, 'expected_daily_result'] = 250 else: group['expected_daily_result'] = group['cum_daily_result'] return group # 按日期分组应用规则 df = df.groupby('date', group_keys=False).apply(process_daily_target) print(df)
输出结果
| date | ID | cum_daily_result | expected_daily_result |
|---|---|---|---|
| 2024-05-01 | 1 | 100 | 100 |
| 2024-05-01 | 2 | 250 | 250 |
| 2024-05-01 | 3 | 300 | 250 |
| 2024-05-02 | 1 | 200 | 200 |
| 2024-05-02 | 2 | 260 | 250 |
内容的提问来源于stack exchange,提问作者siva
相关产品推荐
相关产品推荐

