I have this dataframe and trying to select the last n (=2) rows if the present value is True so I code as below:
df = pd.DataFrame({'A':[10,20,30,40,50,60],'B':[False,False,True,False,True,False]})
A B
0 10 False
1 20 False
2 30 True # Here, I should select 30,20
3 40 False
4 50 True # Here, I should select 50,40
5 60 False
cl_id = df.columns.tolist().index('B') ### cl_id for index number of the column for using in .iloc
op = [df['A'].iloc[x+1-n:x+1,cl_id] if all(df['B'].iloc[x]) for x in np.arange(2,len(df))]
It throws me an error saying invalid syntax.
I want to select the last 2 values in column A if column B value is True My expected output:
opdf =
A B
1 20 False
2 30 True # Here, I should select 30,20
3 40 False
4 50 True # Here, I should select 50,40