简体   繁体   中英

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)

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)

Try this:

import numpy as np
myarray = np.array([[0,3,4,5],[9,4,0,4],[1,2,3,4]])
ix = np.in1d(myarray.ravel(), 0).reshape(myarray.shape)

Output of ix:

array([[ True, False, False, False],
       [False, False,  True, False],
       [False, False, False, False]], dtype=bool)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM