Reputation: 840
I have this 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 want to get the 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]
Upvotes: 1
Views: 48
Reputation: 1053
Another way to do this is by taking the bit difference and seeing the last time it goes from 0 to 1, and using that as an index to the array.
df.iloc[(df.val.diff().drop_duplicates(keep='last') == 1)
.idxmax():]
Output:
name val
4 E 1
5 F 1
6 G 1
Upvotes: 1
Reputation: 150745
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
Upvotes: 2