python - FutureWarning : elementwise comparison failed; returning scalar, 但将来会执行元素比较

标签 python python-3.x pandas numpy matplotlib

我在 Python 3 上使用 Pandas 0.19.1。我收到关于这些代码行的警告。我正在尝试获取一个列表,其中包含字符串 Peter 在列 Unnamed: 5 中存在的所有行号。

df = pd.read_excel(xls_path)
myRows = df[df['Unnamed: 5'] == 'Peter'].index.tolist()

它会产生一个警告:

"\Python36\lib\site-packages\pandas\core\ops.py:792: FutureWarning: elementwise 
comparison failed; returning scalar, but in the future will perform 
elementwise comparison 
result = getattr(x, name)(y)"

什么是 FutureWarning,我应该忽略它,因为它似乎有效。

最佳答案

这个 FutureWarning 不是来自 Pandas,它来自 numpy,这里是如何在更接近问题根源的地方重现警告:

import numpy as np
print(np.__version__)   # Numpy version '1.12.0'
'x' in np.arange(5)       #Future warning thrown here

FutureWarning: elementwise comparison failed; returning scalar instead, but in the 
future will perform elementwise comparison
False

使用双等号运算符重现此错误的另一种方法:

import numpy as np
np.arange(5) == np.arange(5).astype(str)    #FutureWarning thrown here

这是怎么回事?

在将字符串与 numpy 的数字类型进行比较时,Numpy 和原生 python 之间存在分歧。注意右边的操作数是python的地盘,一个原始字符串,中间的操作是python的地盘,但左边的操作数是numpy的地盘。您应该返回 Python 风格的标量还是 bool 的 Numpy 风格的 ndarray? Numpy 说 ndarray of bool,Pythonic 开发人员不同意。经典对峙。

如果元素存在于数组中,应该是元素比较还是标量?

如果您的代码或库使用 in== 运算符将 python 字符串与 numpy ndarrays 进行比较,它们不兼容,所以当你尝试它时,它返回一个标量,但仅限于现在。警告表明,将来这种行为可能会改变,因此如果 python/numpy 决定采用 Numpy 样式,您的代码就会到处乱扔垃圾。

提交的错误报告:

Numpy 和 Python 处于对峙状态,目前该操作返回一个标量,但 future 可能会改变。

https://github.com/numpy/numpy/issues/6784

https://github.com/pandas-dev/pandas/issues/7830

两种变通解决方案:

锁定您的 python 和 numpy 版本,忽略警告并期望行为不会改变,或者将 ==in 的左右操作数转换为来自 numpy 类型或原始 python 数字类型。

全局禁止警告:

import warnings
import numpy as np
warnings.simplefilter(action='ignore', category=FutureWarning)
print('x' in np.arange(5))   #returns False, without Warning

逐行抑制警告。

import warnings
import numpy as np

with warnings.catch_warnings():
    warnings.simplefilter(action='ignore', category=FutureWarning)
    print('x' in np.arange(2))   #returns False, warning is suppressed

print('x' in np.arange(10))   #returns False, Throws FutureWarning

只需按名称禁止警告,然后在它旁边放一个响亮的评论,提到当前版本的 python 和 numpy,说这段代码很脆弱,需要这些版本,并在这里放一个链接。把 jar 踢下去。

TLDR: pandas 是绝地; numpy 是小屋;而python就是银河帝国。

关于python - FutureWarning : elementwise comparison failed; returning scalar, 但将来会执行元素比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40659212/

相关文章:

python - 权限错误 : [Errno 13] Permission denied: despite granting permission in Dockerfile - what could be the issue?

python - 将 pandas 中的索引更改为日期/时间类型?

python - 在 Google App Engine 上获取 DISTINCT 用户

python - 如何查找 S3 存储桶内文件夹的大小?

python - 在 Python 字典中动态创建键和值

python - 如何将字典转换为 Pandas DataFrame,并将特定键作为 Python 中的列名称?

python - Python中IF语句的评估

python - 查找任何开始日的一周开始时间的更简单方法

python - 使用 Python 中的 Pandas,仅选择 group by group count 为 1 的行

python - 在执行一些额外操作的同时将数据帧重新采样为新数据帧