Pandas按3天重采样时对重量求和列设置超1000停止条件的写法
Pandas 3天重采样带阈值求和实现方案
你目前的无条件重采样逻辑是对每个buyer_id分组后按3天窗口对actual_weight求和,要加阈值限制可以通过自定义聚合函数实现,以下是两种常见阈值逻辑的实现代码:
场景1:单个3天窗口求和结果超过1000就截断为1000
适合要求每个独立窗口的求和结果不超过1000的场景:
import pandas as pd # 自定义带阈值的求和函数 def threshold_sum(x, max_val=1000): total = x.sum() return min(total, max_val) # 替换原来的sum方法为自定义函数 data1 = data.groupby('buyer_id').resample('3D', on='wh_inbound_sg_time').actual_weight.apply(threshold_sum)
按你给出的示例结果,该逻辑下buyer_id=64155对应2021-09-06窗口的1964会被截断为1000,其余窗口结果保持不变。
场景2:按时间顺序累计所有窗口的和,超过1000后后续窗口停止求和
适合要求同一个buyer_id下所有窗口累计求和到1000后,后面的窗口不再计算的场景:
import pandas as pd def cumulative_threshold_sum(group_df, max_total=1000): # 先按入库时间排序保证时序正确 sorted_df = group_df.sort_values('wh_inbound_sg_time') # 先计算每个3天窗口的原始求和结果 window_sums = sorted_df.resample('3D', on='wh_inbound_sg_time').actual_weight.sum() # 计算累计和定位超过阈值的位置 cum_total = window_sums.cumsum() over_pos = cum_total[cum_total > max_total].index.min() if pd.notna(over_pos): # 超过阈值后的所有窗口结果置为0 window_sums.loc[over_pos:] = 0 # 如果需要最后一个窗口仅补充到阈值,替换上一行为: # prev_cum = cum_total.shift(1).fillna(0).loc[over_pos] # window_sums.loc[over_pos] = max_total - prev_cum return window_sums # 按buyer_id分组后应用自定义函数 data1 = data.groupby('buyer_id', group_keys=False).apply(cumulative_threshold_sum)
按你给出的示例结果,该逻辑下buyer_id=64155对应2021-09-06窗口之后的所有结果都会被置为0。
注意事项
- 运行前请确认
wh_inbound_sg_time字段已转换为pandas datetime格式,否则重采样会报错 - 可根据实际业务需求调整自定义函数中的阈值数值和超出后的处理逻辑
内容的提问来源于stack exchange,提问作者sherry sun
相关产品推荐
相关产品推荐

