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

如何在Pandas中基于现有列创建滚动5日平均新列?

解决Pandas计算当前行后5行平均值的需求

核心思路

根据你的需求,需要计算当前行之后最多5行的QUANTITY平均值,规则为:

  • 当后续有5行数据时,取这5行的算术平均值
  • 当后续有2-4行数据时,取这些数据的总和除以5
  • 当后续只有1行数据时,直接取该行的数值
  • 最后一行无后续数据,AVG设为0

代码实现

假设你的DataFrame变量名为df,可以通过以下步骤实现:

  1. (可选)修正日期格式并确保顺序正确
    先处理DATE列的格式错误,转换为datetime类型并按降序排列(匹配你的示例数据顺序):
import pandas as pd

# 重置索引并修正日期格式
df = df.reset_index(drop=True)
df['DATE'] = pd.to_datetime(df['DATE'].str.replace('01/010/', '01/10/'), format='%m/%d/%Y')
# 重新设置DATE为索引并按降序排列
df = df.set_index('DATE').sort_index(ascending=False)
  1. 计算AVG列
    通过shift和rolling结合自定义逻辑实现:
import numpy as np

# 取当前行之后的QUANTITY数据
shifted_quant = df['QUANTITY'].shift(-1)
# 计算滑动窗口内的总和与有效数据量
rolling_sum = shifted_quant.rolling(window=5, min_periods=1).sum()
rolling_count = shifted_quant.rolling(window=5, min_periods=1).count()

# 根据有效数据量计算AVG
df['AVG'] = np.where(rolling_count == 5, rolling_sum / 5,
                     np.where(rolling_count == 1, rolling_sum,
                              rolling_sum / 5))
# 最后一行无后续数据,设为0
df['AVG'].iloc[-1] = 0

验证结果

运行上述代码后,得到的结果将完全匹配你提供的示例:

DATEQUANTITYAVG
2024-01-1066.4
2024-01-0936.4
2024-01-0875.4
2024-01-0775
2024-01-06114
2024-01-0543.2
2024-01-0432.6
2024-01-0322.2
2024-01-0256
2024-01-0160

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 00:50:59