How to extract row before and after when flag change from 0 to 1

Viewed 90

I have one dataframe , i want to extract 2 rows before flag change from 0 to one and get row where value 'B' is minimum , also extract two rows after flag 1 and get row with minimum value of 'B'

df=pd.DataFrame({'A':[1,3,4,7,8,11,1,15,20,15,16,87],
                 'B':[1,3,4,6,8,11,1,19,20,15,16,87],
                 'flag':[0,0,0,0,1,1,1,0,0,0,0,0]})

df_out=pd.DataFrame({'A':[4,1],
                     'B':[4,1],
                     'flag':[0,1]})
1 Answers

To find indices of both rows of interest, run:

ind1 = df[df.flag.shift(-1).eq(0) & df.flag.shift(-2).eq(1)].index[0]
ind2 = df[df.index > ind1].B.idxmin()

For your data sample the result is 2 and 6.

Then, to retrieve rows with these indices, run:

df.loc[[ind1, ind2]]

The result is:

   A  B  flag
2  4  4     0
6  1  1     1
Related