Python – Replaces elements in numpy arrays with certain conditions

Replaces elements in numpy arrays with certain conditions… here is a solution to the problem.

Replaces elements in numpy arrays with certain conditions

< partition >

For example, I have some arrays like this:

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

How do I replace all elements greater than a with b, otherwise set them to 0?

I tried

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

But it didn’t work out.

Related Problems and Solutions