Chethan
Chethan

Reputation: 611

After applying certain condition, retain the 1st True row and all other False rows in pandas

After applying certain conditions to dataframe, below is the result of boolean expression row-wise.

s = pd.Series([True,False,True,False,True,False,False,False])

I want to retain the 1st True row and all other False rows.

Expected output:

Output rows of below condition:

output = pd.Series([True,False,False,False,False,False])

How to do it?

Upvotes: 1

Views: 418

Answers (2)

Shubham Sharma
Shubham Sharma

Reputation: 71689

Series.append

s[s].head(1).append(s[~s])

0     True
1    False
3    False
5    False
6    False
7    False
dtype: bool

Upvotes: 4

Quang Hoang
Quang Hoang

Reputation: 150785

Try with:

s[s.cumsum().eq(1)   # first True row
  | (~s)             # or the False rows
 ]

Output:

0     True
1    False
3    False
5    False
6    False
7    False
dtype: bool

Upvotes: 2

Related Questions