Pandas vs. PEP8:选择具有混合类型的系列中的真值

问题描述 投票:2回答:1

我有一个DataFrame名为df,列col包含值TrueFalse"N/A"(类型分别为boolboolstr)。我想只选择包含True的行。

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

有符合PEP8标准的方法吗?

python pandas pep8
1个回答
1
投票

之前曾问过类似的问题,例如pandas: Do I have to deviate from style conventions (PEP 8)?,但它们都描述了一个简单的例子,你只有一列TrueFalse值。在那种情况下,你可以只做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.notnullpd.Series.notna>>> df = df.replace('N/A', np.nan) >>> df[df.col.notnull() & df.col] col 0 True
© www.soinside.com 2019 - 2024. All rights reserved.