Zanam Zanam - 5 months ago 127
Python Question

numpy where operation on 2D array

I have a numpy array 'A' of size 571x24 and I am trying to find the index of zeros in it so I do:

>>>A.shape
(571L, 24L)

import numpy as np
z1 = np.where(A==0)


z1 is a tuple with following size:

>>> len(z1)
2
>>> len(z1[0])
29
>>> len(z1[1])
29


I was hoping to create a z1 of same size as A. How do I achieve that?

Edit: I want to create array z1 of booleans for presence of zero in A such that:

>>>z1.shape
(571L, 24L)

Answer

You can just check this with the equality operator in python with numpy. Example:

>>> A = np.array([[0,2,2,1],[2,0,0,3]])
>>> A == 0
array([[ True, False, False, False],
       [False,  True,  True, False]], dtype=bool)

np.where() does something else, see documentation. Although, it is possible to achieve this with np.where() using broadcasting. See documentation.

>>> np.where(A == 0, True, False)
array([[ True, False, False, False],
       [False,  True,  True, False]], dtype=bool)
Comments