Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I logically test the output of a np.where result?

I was trying to scan an array for values and take action depending on the result. However, when I had a closer look at what the code was doing I noticed that my logical condition was ill posed.

I will illustrate what I mean with the following example:

#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)

I was expecting my index to return an empty list. In fact it returns a tuple object, like:

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

So, the test I was imposing:

#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.')

Will not achieve its purpose because I was comparing different objects (is that correct to say?).

So what is the correct way to create this test?

Thanks for your time!

like image 272
Chicrala Avatar asked Oct 28 '25 09:10

Chicrala


1 Answers

For your 2D array, np.where returns a tuple of arrays of indices (one for each axis), so that a[index] gives you an array of the elements fulfilling the condition.

Indeed, you compared an empty list to an empty array. Instead, I would compare the size property (or e.g. len()) of the first element of this tuple:

if index[0].size == 0:
    print('No values found.')
like image 137
jan Avatar answered Oct 30 '25 00:10

jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!