Home > OS >  Why is numpy.where() returning 2 arrays?
Why is numpy.where() returning 2 arrays?

Time:01-27

I am confused with numpy function np.where(). For example if we have:

b = np.array([[1, 2, 3, 4, 5,6], [1,0,3,0,9,6]])
f = np.where(b)

output

print(f)
(array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]), array([0, 1, 2, 3, 4, 5, 0, 2, 4, 5]))

Here, array b contains 2 rows and 6 columns. I am unsure as to why np.where outputs two arrays, but a 2d array might be the reason. However, each array contains ten elements; how this comes?

CodePudding user response:

From the documentation of numpy.where:

When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.

b = np.array([[1, 2, 3, 4, 5,6], [1,0,3,0,9,6]])
f = np.where(b) # b.nonzero()

r,c = b.nonzero()
print(r)
>> array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1])
print(c)
>>array([0, 1, 2, 3, 4, 5, 0, 2, 4, 5])

np.nonzero gives indices of nonzero elements in rows and columns.

CodePudding user response:

b is a 2D array with 2 rows and 6 columns.

col 0 col 1 col 2 col 3 col 4 col 5
row 0 1 2 3 4 5 6
row 1 1 0 3 0 9 6

The numpy.where() function returns a tuple of arrays, containing the indices of the elements in the input array that satisfy the given condition.

b = np.array([[1, 2, 3, 4, 5,6], [1, 0, 3, 0, 9, 6]])
f = np.where(b)

When you call np.where(b), it returns two arrays, one for the row indices and one for the column indices of the elements in b that are not equal to zero. The first array contains the row indices and the second array contains the column indices of the non-zero elements of b.

print(f)
(array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1])  # <<< row 
 array([0, 1, 2, 3, 4, 5, 0, 2, 4, 5])) # <<< col 

If combined, the two arrays would look like this.
(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 0), (1, 2), (1, 4), (1, 5)

So the result would be 10 pairs of rows and columns since there are 10 values that meet the criteria. Let's bold the targets that meet the conditions again on the table.

col 0 col 1 col 2 col 3 col 4 col 5
row 0 1 2 3 4 5 6
row 1 1 0 3 0 9 6
  • Related