在使用numpy找到指定元素对应索引时,一般会使用numpy.argwhere()或numpy.where()函数。

正常使用numpy.argwhere()函数时,返回结果是元素的坐标。

但是当数组内没有指定元素时,会返回[],比如下面这段程序

import numpy
x = numpy.arange(5) #[0,1,2,3,4]
y = numpy.argwhere(x==5)

输出y时结果为[]

print(y) #[]

查看y的布尔值时,结果为False

print(bool(y)) #False

并报错

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.

根据Python提示,可以使用array.size来判断数组是否为空。

print(y.size) # 0

修改程序发现空数组的值为0,而非空数组的值>0。

因此可以使用这个方式来判断空数组。

物联沃分享整理
物联沃-IOTWORD物联网 » Python空数组判断

发表评论