I am trying to do a rolling count of how many of the last 5 rows are positive in a dataframe. An example of this would be:
Values | Positive last 5
------------------------
1 1
4 2
-9 2
6 3
1 4
-1 3
-3 2
4 3
CodePudding user response:
Create mask for compare greater values like 0
and then count True
s by sum
in Series.rolling
:
df['new'] = df['Values'].gt(0).rolling(5, min_periods=1).sum().astype(int)
print (df)
Values Positive last 5 new
0 1 1 1
1 4 2 2
2 -9 2 2
3 6 3 3
4 1 4 4
5 -1 3 3
6 -3 2 2
7 4 3 3