【问题标题】:After applying certain condition, retain the 1st True row and all other False rows in pandas应用特定条件后,保留 pandas 中的第一个 True 行和所有其他 False 行
【发布时间】:2021-06-24 19:27:57
【问题描述】:

对数据框应用某些条件后,以下是布尔表达式逐行的结果。

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

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

预期输出:

以下条件的输出行:

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

怎么做?

【问题讨论】:

  • 我会尝试制作 2 个面具,1 个为真,一个为假。然后只保留第一行的真实值。速度成为一个有趣的问题...

标签: python python-3.x pandas python-2.7 dataframe


【解决方案1】:

Series.append

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

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

【讨论】:

    【解决方案2】:

    尝试:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      • 2018-11-02
      • 2020-10-23
      • 1970-01-01
      • 2022-11-20
      • 2022-07-21
      相关资源
      最近更新 更多