1

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.

2
  • 3
    FYI, df.rolling (or that of a Series) has a parameter center that you can pass True. Commented Jan 15, 2022 at 13:07
  • I tried to edit this question to make it easier for people with this same question to find in the future, though the suggested edit queue is full. Commented Jan 15, 2022 at 15:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.