python array operation with index

Viewed 30

I try to design a array operation which describe below:

if a element in an array is less than 0, then new value should set to 0. else the new value should be the square of the original value.

e.g.
import numpy as np
input = np.array([-2, 5, 2, -1])
#some operation ...
#input should be: [0, 25, 4, 0]

Also, I want to make this operation can take arbitrary input dimension(2D array, 3D array ...)

I can only thought of this solution:

input = np.array([-2, 5, 2, -1])
input[input < 0] = 0  # input = [0 5 2 0]
#input[input >= 0] = input*input   <- this will cause error

I already know how to complete negative part, but I don't know how to deal with square part, can someone help me out?

Thanks a lot!

1 Answers

Simply use numpy's where function :

output = np.where(input <= 0, 0, input**2)
Related