Home > Back-end >  Pandas Window Function
Pandas Window Function

Time:01-16

I need a function that returns the average of a specific window of pandas. Let's say our data is in the nth row. My window needs to sum ( n-2, n-1, n, n 1, n 2) and find the average. Pandas has rolling functions but I think it only does that in one direction one not in 2 directions at the same time.

CodePudding user response:

This solution implements what was described by Neither, using a centered window.

>>> 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

Note that for centered windows of n elements, where n is odd, the first and last n // 2 elements will be NaN, as they aren't the center of any window.

  •  Tags:  
  • Related