Find average of last 14 values in pandas column excluding values that are 0

You are asking for rolling().sum():

N = 14

df['col1'].rolling(N).sum()/df['col1'].ne(0).rolling(N).sum()

Output:

0          NaN
1          NaN
2          NaN
3          NaN
4          NaN
5          NaN
6          NaN
7          NaN
8          NaN
9          NaN
10         NaN
11         NaN
12         NaN
13    3.916667
14    4.166667
15    4.272727
16    4.100000
17    4.100000
18    4.100000
19    4.181818
Name: col1, dtype: float64

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top