Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

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

1 Answer

0 votes
by (36.8k points)

You can try limit with bfill

n = 2

df[df.B.where(df.B).bfill(limit=n-1)==1]

Out[95]: 

    A      B

1  20  False

2  30   True

3  40  False

4  50   True

Do check out Data Science with Python course which helps you understand from scratch 

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...