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

Pandas索引降序时如何实现滚动求和、滚动均值等滚动窗口统计

最简洁的实现方案

如果你使用 pandas 1.3.0及以上版本,直接用rolling方法自带的reverse=True参数即可,无需手动反转数据:

ans = df.rolling(2, reverse=True).mean()

这个输出和你现有写法完全一致,一行就能搞定,比两次iloc[::-1]反转的写法可读性和性能都更好。


其他可选优化方案

  • 如果需要兼容低版本pandas,你可以把自定义方法注册为pandas访问器,调用起来比pipe更方便:
# 注册自定义滚动访问器
import pandas as pd
@pd.api.extensions.register_dataframe_accessor("irolling")
@pd.api.extensions.register_series_accessor("irolling")
class InverseRolling:
    def __init__(self, data):
        self.data = data
    def __call__(self, aggfunc, **kwargs):
        return self.data.iloc[::-1].rolling(**kwargs).agg(aggfunc).iloc[::-1]

# 注册后直接调用即可,无需额外传参
ans = df.irolling('mean', window=2)
  • 如果你的数据索引本身是时间维度,建议先把索引转为时间类型,用时间偏移量定义窗口,不需要依赖索引的排序方向:
# 转时间索引
df.index = pd.to_datetime(df.index)
# 用自然年窗口计算,不受索引排序影响
ans = df.rolling(window='2YE').mean()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:54:03