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

无法使用pandas的rolling_mean等滚动函数,求解决方案及window参数用法

Hey there! Let's work through this pandas issue step by step.

Fixing the AttributeError for rolling_mean & Similar Functions

Why the error happens?

You referenced pandas 0.17.0 docs where pandas.rolling_mean does exist, but starting from pandas 0.18.0, the team restructured the rolling statistics API. Those top-level rolling_* functions were moved under the DataFrame.rolling() method to create a more consistent interface. If your installed pandas version is 0.18.0 or newer, calling pd.rolling_mean() directly will throw this error because the function is no longer in the top-level pandas module.

Correct code for newer pandas versions

Here's how to rewrite your code to work with modern pandas:

import pandas as pd 
df = pd.DataFrame({
    'a':[1,2,3,4,5,6,7,8,9,10], 
    'b':[11,12,13,14,15,16,17,18,19,20], 
})
# Rolling mean (replaces pd.rolling_mean)
df.rolling(window=2).mean()

# For the other functions you mentioned:
df.rolling(window=2).median()  # Replaces pd.rolling_median
df.rolling(window=2).var()     # Replaces pd.rolling_var

How the window parameter works

  • window sets the size of the sliding window, meaning how many consecutive rows of data are used to calculate the statistic. When you set window=2, each result (starting from the second row) is computed using the current row and the immediately preceding row.
  • For your sample data, the first row will return NaN because there's no prior row to form a window of size 2. Subsequent rows will show the average (or median/variance) of the current and previous row:
    a     b
    

0 NaN NaN
1 1.5 11.5
2 2.5 12.5
3 3.5 13.5
... and so on

- If you're working with time-series data, `window` can also accept a time-based string (like `window='3D'` for a 3-day window) — just make sure your DataFrame's index is a datetime type first.

内容的提问来源于stack exchange,提问作者kovac
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:27:16