Python报错:The truth value of an array with more than one element is ambiguous
程序员文章站
2022-05-27 12:50:10
...
前言
程序员的一生就是和bug作战的一生,为了方便后来人以及自己的偶尔复习,特此写下本篇,记录自己的错误。
目录
正文
在使用python的时候,总是会遇到一些奇特的错误,在调用numpy包后,会经常遇到这个错误:
DeprecationWarning: The truth value of an empty array is ambiguous.
Returning False, but in future this will
result in an error. Use `array.size > 0` to check that an array is not empty.
今天我们就来解决这个问题:
解决方案
Numpy对逻辑表达式判别不清楚,它可以返回False如果等号两边两个式子是数值相等,也可以返回True因为等号两边两个式子是逻辑相等。它觉得这是模棱两可的,因此放弃做判断,统一用a.any()进行或比较,或a.all()进行与比较。可以从下面例子体会一下。
import numpy as numpy
a=np.zeros(3)
a[0]=0; a[1]=2; a[2]=1
print (a-[0,2,1]).any() #[0,0,0] False
print (a-[0,2,1]).all() #[0,0,0] False
print (a-[1,3,2]).any() #[-1,-1,-1] True
print (a-[1,3,2]).all() #[-1,-1,-1] True
print (a-[0,3,2]).any() #[0,-1,-1] True
print (a-[0,3,2]).all() #[0,-1,-1] False
numpy-array数组进行(a-b)比较时,True表示不同,False表示相同
部分元素相等,numpy.all() 返False(一帮情况下不希望出现),numpy.any() 返回True; 所有元素都相等,二者均返回False 因此最好使用numpy.any() 比较
上一篇: python报错ValueError: The truth value of an array with more than one element is ambiguous. Use a.any()
推荐阅读
-
moviepy AudioClip帧处理ValueError: The truth value of array with more than one element is ambiguous
-
python报错ValueError: The truth value of an array with more than one element is ambiguous. Use a.any()
-
Python报错:The truth value of an array with more than one element is ambiguous
-
Python ValueError: The truth value of an array with more than one element is ambiguous.
-
成功解决Python的ValueError: The truth value of an array with more than one element is ambiguous
-
moviepy AudioClip帧处理ValueError: The truth value of array with more than one element is ambiguous
-
[numpy问题]The truth value of an array with more than one element is ambiguous.
-
学习随笔-ValueError: The truth value of an array with more than one element is ambiguous
-
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or
-
moviepy AudioClip帧处理ValueError: The truth value of array with more than one element is ambiguous