Skip to content Skip to sidebar Skip to footer

What Is The Best Way To Check If The Last Rows Of A Pandas Dataframe Meet A Set Of Conditions?

This question is a follow-up of the follow question: What is the best way to check if the last rows of a pandas dataframe meet a condition? But I got stuck trying to modify the ans

Solution 1:

You need another rolling(3) as follows

m1 = df.rolling(5).sum().eq(5)
m2 = df.eq(0).rolling(3).sum().eq(3)
df['check'] = df[m1 | m2].ffill()

Out[310]:
       signal  check
index01    NaN
11    NaN
21    NaN
31    NaN
411.0511.0601.0701.0800.0900.01000.01100.01200.01310.01400.01510.01610.01710.01810.01911.0

Mask m2 could also be simplified to this

m2 = df.rolling(3).sum().eq(0)

Solution 2:

First select the last 5 rows of a dataframe and select the column, then check if all the results are equal to some value (ie: 1 for CRITERIA 1).

import numpy as np if np.all(df[-5:]['signal'] == 1): print('CRITERIA 01 is met')

Then you can build the other criterias similarly.

Post a Comment for "What Is The Best Way To Check If The Last Rows Of A Pandas Dataframe Meet A Set Of Conditions?"