Skip to main content
 首页 » 编程设计

python之Pandas 与 PEP8 : Selecting True values in a Series with mixed types

2024年11月24日7zhoujg

我有一个名为 df 的 DataFrame,其中有一列 col 包含值 True、False 和 "N/A"(类型分别为 bool、bool 和 str)。我只想选择包含 True 的行。

df[df.col==True] 有效,但生成警告 PEP 8: comparison to True should be 'if cond is True:' or 'if cond:'.

是否有符合 PEP8 标准的方法来执行此操作?

请您参考如下方法:

之前问过类似的问题,比如pandas: Do I have to deviate from style conventions (PEP 8)? ,但它们都描述了一个简单的情况,您有一列只有 True 和 False 值。在这种情况下,您可以只执行 df[df.col]。

在你的情况下你不能这样做,因为它会给出一个错误,但你有一些其他的选择:

  1. 使用 pd.Series.eq :

    >>> df = pd.DataFrame({'col': [True, False, 'N/A']}) 
    >>> df[df.col.eq(True)] 
        col 
    0  True 
    
  2. 首先检查 “N/A”,然后比较剩余的内容是否为 True。订单事项:

    >>> df[(df.col != 'N/A') & df.col] 
        col 
    0  True 
    
  3. 将 "N/A" 替换为 np.nan 并使用 pd.Series.notnull或 pd.Series.notna :

    >>> df = df.replace('N/A', np.nan) 
    >>> df[df.col.notnull() & df.col] 
        col 
    0  True