FutureWarning:elementwise比较失败;改为返回标量

2024-04-20 13:46:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我收到一个警告,我想看看这是否会打破。我在很多情况下都使用np.where(对我来说,它类似于excel中的if语句)。有没有更好或更多的Python或熊猫的方式来做到这一点?我正试图把一维变成一种我可以很容易地做数学运算的东西。

df['closed_item'] = np.where(df['result']=='Action Taken', 1, 0)

FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  result = getattr(x, name)(y)


INSTALLED VERSIONS
------------------
python: 3.5.1.final.0
python-bits: 64
OS: Windows
OS-release: 10

pandas: 0.18.0
nose: 1.3.7
pip: 8.1.0
setuptools: 20.2.2
Cython: 0.23.4
numpy: 1.11.0
scipy: 0.17.0
statsmodels: 0.6.1
xarray: None
IPython: 4.0.0
sphinx: 1.3.1
patsy: 0.4.0
dateutil: 2.4.2
pytz: 2015.7
blosc: None
bottleneck: None
tables: 3.2.2
numexpr: 2.5.1
matplotlib: 1.5.1
openpyxl: 2.2.6
xlrd: 0.9.4
xlwt: 1.0.0
xlsxwriter: 0.7.7
lxml: 3.4.4
bs4: 4.4.1
html5lib: None
httplib2: None
apiclient: None
sqlalchemy: 1.0.9
pymysql: None
psycopg2: None
jinja2: 2.8
boto: 2.38.0

Tags: none警告dfifosnp方式情况
1条回答
网友
1楼 · 发布于 2024-04-20 13:46:26

你提到的问题其实很复杂,所以让我用你的话把它分成几个部分:

I am receiving a warning and I want to check if this will break

Warning是一个语句,它告诉您在处理编码逻辑时要小心。一个设计良好的警告不会破坏代码;如果是这样,它将是一个Exception

虽然您需要注意输出或性能是否有问题,但通常您可能会忽略警告ceteris paribus。因此,在您的情况下,如果其他一切正常,并且您不打算更新软件,则不需要做任何事情来抑制警告。但是,如果需要,可以使用以下代码段:

import warnings
with warnings.catch_warnings():
    warnings.filterwarnings('ignore', r'elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison(.*)')

I am using np.where like this in a lot of cases (it is similar, for me, to an if statement in excel).

请注意,pandas中有一个DataFrame.where方法。

Is there a better or more pythonic or pandas way to do this?

是的,有两种方法可以使代码更像熊猫: 如果你想得到一些像傻瓜一样工作的列,你可以使用

pd.get_dummies(df.result)

它将生成一个数据帧,其中包含在序列中可能找到的所有伪值。 如果你觉得这听起来有点过头了,别担心有办法只找出一个这样的变量。


在pandas中,booleanTrueFalse通常用于对序列或数据帧中的匹配进行二进制分类,因此在您的情况下,可以执行以下操作:

df.closed_item = df.result == 'Action Taken'

I'm trying to turn one dimension into something I can easily do mathematical operations on.

但是,如果希望输出包含整数值以便与您的输出匹配,则可以使用以下代码:

df.closed_item = (df.result == 'Action Taken'`).astype(int)

作为补充说明,我认为此警告不会传播到较新版本,即0.13及更高版本(正如预期的那样,因为它是未来的警告),因此您也可以考虑更新。

相关问题 更多 >