Replace element in numpy array using some condition

For example, I have some array like:

>>> x = np.arange(-5, 4).reshape(3, 3)
>>> x
array([[-5, -4, -3],
       [-2, -1,  0],
       [ 1,  2,  3]])

      

How can I replace all elements b

that are greater than a

, otherwise set them to 0

?

I tried

np.place(x, lambda y: b if y > a else 0)

      

But it didn't work.

+3


source to share


2 answers


You can use numpy.where

:



x = np.arange(-5, 4).reshape(3, 3)
x
#array([[-5, -4, -3],
#       [-2, -1,  0],
#       [ 1,  2,  3]])

b = 1; a = 0;
np.where(x > a, b, 0)
#array([[0, 0, 0],
#       [0, 0, 0],
#       [1, 1, 1]])

      

+2


source


Not as good as np.where

, but in your case you can simply multiply the "logical array", which you get when you are comparing your array a

using b

:

>>> x = np.arange(-5, 4).reshape(3, 3)
>>> a, b = 0, 6
>>> (x > a) * b
array([[0, 0, 0],
       [0, 0, 0],
       [6, 6, 6]])

      



This works because it is True

equivalent to 1

and False

- 0

in arithmetic operations.

+1


source







All Articles