如何逻辑测试np.where结果的输出



我试图扫描数组中的值,并根据结果采取行动。然而,当我仔细观察代码在做什么时,我注意到我的逻辑条件是不合理的。

我将用下面的例子来说明我的意思:

#importing numpy
import numpy as np
#creating a test array
a = np.zeros((3,3))
#searching items bigger than 1 in 'a'
index = np.where(a > 1)

我希望我的索引返回一个空列表。事实上,它返回一个元组对象,如:

index
Out[5]: (array([], dtype=int64), array([], dtype=int64))

所以,我强加的测试:

#testing if there are values
#in 'a' that fulfil the where condition 
if index[0] != []:
print('Values found.')
#testing if there are no values
#in 'a' that fulfil the where condition
if index[0] == []:
print('No values found.')

不会达到它的目的,因为我在比较不同的对象(这样说正确吗?(。

那么,创建这个测试的正确方法是什么呢?

谢谢你抽出时间!

对于您的2D数组,np.where返回一个索引数组元组(每个轴一个(,因此a[index]为您提供一个满足条件的元素数组。

实际上,您将空列表与空数组进行了比较。相反,我会比较这个元组的第一个元素的size属性(例如len()(:

if index[0].size == 0:
print('No values found.')

最新更新