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

如何基于Pandas DataFrame历史行其他列值高效生成计算新列

解决方案

你可以用Pandas内置的pd.merge_asof接口实现需求,它专门处理这类近似匹配场景,性能远高于逐行遍历,一行代码实现如下:

df['quantity_3days_ago'] = pd.merge_asof(df.assign(target_days=lambda x: x['days'] - 3), df, left_on='target_days', right_on='days', direction='backward', suffixes=('', '_match'))['quantity_match'].where(df['days'] >= 3)

代码逻辑说明

  • 先通过assign方法为每行生成匹配目标值target_days = 当前行days - 3
  • 调用merge_asof做后向匹配:自动找到小于等于target_days的最大days对应的quantity值
  • 最后通过where方法将days小于3的行的计算结果置为NaN,完全符合规则要求
    运行上述代码后得到的结果和你给出的预期输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:54:04