简体   繁体   中英

How to count positive values of last 5 rows of dataframe

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM