pythonarraysnumpynumpy-ndarrayimage-masking

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)
print(xz)
print(yz)

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?


Solution

  • 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:

    print(np.transpose(np.where(z)))
    

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