Back

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

I have the below data frame

lst = [['A',1],['B',0],['C',1],['D',0],['E',1],['F',1],['G',1]]

df = pd.DataFrame(lst,columns = ['name','val'])

Looks like this

  name  val

0    A    1

1    B    0

2    C    1

3    D    0

4    E    1

5    F    1

6    G    1

I am trying to get rows where val is 1 but they should be bottom continuous rows.

Desired output

  name  val

4    E    1

5    F    1

6    G    1

I am doing, which will give all val with 1.

df[df.val == 1]

1 Answer

0 votes
by (36.8k points)

You can use cumsum to get the last block:

# blocks separated by `0`

s = df.val.ne(1).cumsum()

# last blocks and only value 1

df[s.eq(s.max()) & df['val'].eq(1)]

Output:

  name  val

4    E    1

5    F    1

6    G    1

Learn Python for Data Science Course to improve your technical knowledge. 

Browse Categories

...