在否定布尔索引上使用 any() 时,如何避免 PyCharm 检查器错误?

问题描述

[我更新了标题和问题以反映这是一个 PyCharm 问题,而不是一个通用的 Python 问题。]

我的应用程序的目的是验证一个大数据集,所以我有很多情况,我创建一个布尔索引来测试每一行的条件,然后如果有任何行符合条件,我想打印出所有无效的行。

问题是 PyCharm 检查器不断报告我的布尔索引不可迭代的错误

但是代码运行良好。如何编写我的代码来消除这些错误?我不想只使用布尔索引为每一行添加 PyCharm 检查器异常。 (我使用的是 Python 3.7 和 PyCharm CE 2020.3.3)

请注意,该问题似乎只出现在否定的布尔索引中,因此一种解决方案是从所有布尔索引中消除否定,但这会导致布尔逻辑变得迟钝、不可维护,并且需要手动否定复杂的条件。

这是一个代码示例,显示了 PyCharm 检查器的不一致行为

from pandas import DataFrame

df = DataFrame([[1,2],[3,4],5]],columns=['A','B'])
print(df)

# The following 3 lines get no PyTypeInspector errors
b_idx = ((df.A == 3) & (df.B == 5))
print(b_idx)
print(f'Any #1: {any(b_idx)}')

# But any time a negation is used,the code gets inspector errors
# even though executing the code works fine
b_idx = (~((df.A != 3) | (df.B != 5)))
print(b_idx)

# The following line gets the inspector error:
# ***** Expected type 'Iterable[object]',got 'int' instead
print(f'Any #2: {any(b_idx)}')

# The following line gets the inspector error:
# ***** Unresolved attribute reference 'values' for class 'int'
print(f'Any #3: {b_idx.values.any()}')

# So I tried to tell the inspector that b_idx is a list.
# The following line gets the inspector error:
# ***** Expected type 'Iterable' (matched generic type 'Iterable[_T]'),got 'int' instead
b_idx = list(~((df.A != 3) | (df.B != 5)))

print(b_idx)
print(f'Any #4: {any(b_idx)}')

# One final thing... sometimes I want to force one of the rows to be printed.
# The following statement also gets a inspector error:
# *****  Unresolved attribute reference 'iloc' for class 'bool'
b_idx.iloc[0] = True

运行上述代码的结果是:

   A  B
0  1  2
1  3  4
2  3  5
0    False
1    False
2     True
dtype: bool
Any #1: True
0    False
1    False
2     True
dtype: bool
Any #2: True
Any #3: True
[False,False,True]
Any #4: True

Process finished with exit code 0

对于消除这些检查错误的任何帮助,我们将不胜感激。 谢谢!


更新 - 找到解决方法

我仍然想了解为什么我的原始代码会出现检查器错误,但我已经找到了绕过它们的方法

我所做的是将每个布尔索引转换为一个 numpy 数组,并使用 astype 将其声明为布尔值。这消除了所有检查器警告,但为什么代码没有像最初编写的那样工作?没有前导波浪号 (~) 的布尔索引有效,但有前导波浪号 (~) 失败

这是修改后的代码,没有检查员错误

from pandas import DataFrame
from numpy import array

df = DataFrame([[1,'B'])
print(df)

# The following 3 lines get no inspector errors
b_idx = ((df.A == 3) & (df.B == 5))
print(b_idx)
print(f'Any #1: {any(b_idx)}')

# Converting to ndarray and declaring it boolean eliminates the errors
b_idx = array(~((df.A != 3) | (df.B != 5))).astype(bool)
print(b_idx)
print(f'Any #2: {any(b_idx)}')
# I no longer needed the "values" call
print(f'Any #3: {any(b_idx)}')

# I no longer needed the "list" call
b_idx = array(~((df.A != 3) | (df.B != 5))).astype(bool)
print(b_idx)
print(f'Any #4: {any(b_idx)}')

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)