Home > database >  Pandas delete rows after condition in column "A" until confition in column "B"
Pandas delete rows after condition in column "A" until confition in column "B"

Time:05-23

How do you remove each row after each "close_condition" == 1 until you reach a "open_condition" == 1 row?

No row with "open_condition" == 1 is to be deleted

   open_condition  close_condition
0                1                1
1                0                1
2                0                0
3                0                0
4                0                1
5                0                1
6                1                0
7                1                0
8                1                1
9                0                0
10               1                0
11               1                0
12               0                0
13               1                0
14               0                0
15               0                0
16               1                0
17               0                0
18               1                1
19               0                1

should become

 open_condition  close_condition
0                1                1
6                1                0
7                1                0
8                1                1
10               1                0
11               1                0
12               0                0
13               1                0
14               0                0
15               0                0
16               1                0
17               0                0
18               1                1

CodePudding user response:

You could create a "running close flag" that resets to 0 every time it encounters an open_condition

df['rcf'] = [c if o else np.nan for (o, c) in zip(df['open_condition'], df['close_condition'])]
df['rcf'] = df['rcf'].fillna(method='ffill').astype('int')
df['keep'] = (df['open_condition']   (1 - df['rcf'])).astype(bool)
df[df['keep']]

Output

    open_condition  close_condition  rcf  keep
0                1                1    1  True
6                1                0    0  True
7                1                0    0  True
8                1                1    1  True
10               1                0    0  True
11               1                0    0  True
12               0                0    0  True
13               1                0    0  True
14               0                0    0  True
15               0                0    0  True
16               1                0    0  True
17               0                0    0  True
18               1                1    1  True
  • Related