np.where on 2D array without masked array or any second argument

I was checking out one code snippets, there was a code like below

z = [[True, False, True],[True, True, True],[False, False, False]]
xz, yz = np.where(z)

This returns

[0 0 1 1 1]
[0 2 0 1 2]

If I make

z = [[True, False, True],[True, True, True]]

I will get the same results as

[0 0 1 1 1]
[0 2 0 1 2]

When I make

z = [[True, False],[True, True]]

The result is

[0 1 1]
[0 0 1]

I was not able to find out what's it doing, This was presented in SynthText repo on github. I would be appreciated if any one could help to understand what it does? And what's its application?

2 answers

  • answered 2021-09-11 18:11 Péter Leéh

    If you read carefully the documentation on np.where, you find that it's equvivalent to np.asarray(condition).nonzero() in case you only provide the condition parameter, so the behaviour comes down to np.nonzero.

    >>> z = np.array([[True, False], [True, True]])

    You have three nonzero elements in this array, indexed by: [0, 0], [1, 0], [1, 1]

    >>> np.nonzero(z)
    (array([0, 1, 1], dtype=int64), array([0, 0, 1], dtype=int64))

    The first element of the tuple is the first index of every nonzero element ([0, 1, 1]), the second element of the tuple is the second index of every nonzero element ([0, 0, 1]).

  • answered 2021-09-11 20:50 Ali_Sh

    If we consider 2d-array such as matrices, np.where(z) helps to get elements' indices for which are True or nonzero. 2d-array indices have two components corresponding to each elements of the array as [rows' number, columns' number]. The first variable, i.e. xz in your example, shows the rows' numbers for True or nonzero elements and yz shows the corresponding columns' numbers. The following code could be helpful in understanding:

    xz = [1th-x, 2nd-x, 3rd-x]
    yz = [1th-y, 2nd-y, 3rd-y]
    nonzero_indices = [[1th-x, 1th-y], [2nd-x, 2nd-y], [3rd-x, 3rd-y]]

    Using the following code will get the indices for each True or nonzero elements as it is shown as nonzero_indices in the code above:


    Which will give [[0 0] [1 0] [1 1]]
    Hope it be helpful.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum