numpy:FutureWarning:逐元素比较失败

编码旋钮

关于此SO后的FutureWarning中描述的问题,numpy是否有任何解决方案:按元素比较失败;返回标量,但将来将执行元素比较我的numpy版本是1.19.1并使用python 3.8.5

a = np.array(['aug', False, False, False])

a == 'aug'

array([ True, False, False, False])

但:

a == False

<ipython-input-88-f9ff25cfe387>:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  a == False

与np.nan相同:

a = array(['aug', np.nan, np.nan, np.nan])
a == 'aug'

array([ True, False, False, False])

但:

a == np.nan

<ipython-input-1236-9224919e9367>:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  a == np.nan

False
hpaulj

创建数组后查看它们:

In [58]: a = np.array(['aug', False, False, False])
    ...: 
In [59]: a
Out[59]: array(['aug', 'False', 'False', 'False'], dtype='<U5')
In [60]: a == 'aug'
Out[60]: array([ True, False, False, False])
In [61]: a == False
<ipython-input-61-f9ff25cfe387>:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  a == False
Out[61]: False
In [62]: a == 'False'
Out[62]: array([False,  True,  True,  True])

这是一个字符串dtype数组。测试匹配的字符串有效。测试非字符串值是错误的。

相同nan

In [64]: a = np.array(['aug', np.nan, np.nan, np.nan])
In [65]: a
Out[65]: array(['aug', 'nan', 'nan', 'nan'], dtype='<U3')
In [66]: a == 'nan'
Out[66]: array([False,  True,  True,  True])

如果必须混合使用类型-字符串,布尔值,浮点数,则可以指定objectdtype。这使得数组更像列表。

In [67]: a = np.array(['aug', False, False, False], object)
In [68]: a
Out[68]: array(['aug', False, False, False], dtype=object)
In [69]: a == 'aug'
Out[69]: array([ True, False, False, False])
In [70]: a == False
Out[70]: array([False,  True,  True,  True])
In [71]: a == True
Out[71]: array([False, False, False, False])

但这并没有帮助np.nannan是一种特殊的浮标,它不等于任何东西,甚至不等于本身。

In [72]: a = np.array(['aug', np.nan, np.nan, np.nan], object)
In [73]: a
Out[73]: array(['aug', nan, nan, nan], dtype=object)
In [74]: a=='aug'
Out[74]: array([ True, False, False, False])
In [75]: a == np.nan
Out[75]: array([False, False, False, False])

isnan是测试的正确方法nan,但仅适用于float dtype数组:

In [76]: np.isnan(a)
Traceback (most recent call last):
  File "<ipython-input-76-da86cb21b8a4>", line 1, in <module>
    np.isnan(a)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章