应用特定条件后,保留 pandas 中的第一个 True 行和所有其他 False 行

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

对dataframe应用特定条件后,下面是布尔表达式逐行的结果。

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

我想保留第一个 True 行和所有其他 False 行。

预期输出:

以下条件的输出行:

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

怎么做?

试试:

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

输出:

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

Series.append

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

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