我需要一個函式來回傳特定熊貓視窗的平均值。假設我們的資料在第 n 行。我的視窗需要求和(n-2、n-1、n、n 1、n 2)并找到平均值。Pandas 具有滾動功能,但我認為它只能在一個方向上滾動,而不是同時在兩個方向上滾動。
uj5u.com熱心網友回復:
該解決方案使用居中的視窗實作了既不描述的內容。
>>> import numpy as np
>>> import pandas as pd
>>> series = pd.Series(np.arange(100))
>>> series
0 0
1 1
2 2
3 3
4 4
..
95 95
96 96
97 97
98 98
99 99
Length: 100, dtype: int32
>>> series.rolling(5, center=True).mean()
0 NaN
1 NaN
2 2.0
3 3.0
4 4.0
...
95 95.0
96 96.0
97 97.0
98 NaN
99 NaN
Length: 100, dtype: float64
請注意,對于n元素的居中視窗,其中n是奇數,第一個和最后一個n // 2元素將是NaN,因為它們不是任何視窗的中心。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412448.html
標籤:
