Reputation: 816
If I have a pandas data frame like this:
Col A
0 2
1 3
2 5
3 4
4 6
5 2
6 3
7 1
8 1
9 7
and some odd numerical value like this
n = 3
How do I average the value I'm replacing, the values before, and after based on half of my n. For n = 3 I would be averaging the value before and after. Such that I get a pandas dataframe like this:
Col A Col B
0 2 np.nan
1 3 3.33
2 5 4
3 4 5
4 6 4
5 2 3.67
6 3 2
7 1 2.5
8 1 3
9 7 np.nan
The first and last values are np.nan because there is not a value before/after them.
Upvotes: 1
Views: 125
Reputation: 150785
You can use rolling
with center
option:
n = 3
df['Col A'].rolling(n, center=True).mean()
Output:
0 NaN
1 3.333333
2 4.000000
3 5.000000
4 4.000000
5 3.666667
6 2.000000
7 1.666667
8 3.000000
9 NaN
Name: Col A, dtype: float64
Upvotes: 1