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
index
0 1 NaN
1 1 NaN
2 1 NaN
3 1 NaN
4 1 1.0
5 1 1.0
6 0 1.0
7 0 1.0
8 0 0.0
9 0 0.0
10 0 0.0
11 0 0.0
12 0 0.0
13 1 0.0
14 0 0.0
15 1 0.0
16 1 0.0
17 1 0.0
18 1 0.0
19 1 1.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?"