I have a numpy array x and I would like to perform an action on the elements of x depending on its value. For example suppose I want to take the square for all negative elements and take the fourth power for all the other elements. The following code does the trick
import numpy as np
x = np.array([-2,-1,0,1,2,3])
y = np.zeros(len(x))
for i in range(len(x)):
if x[i]<0:
y[i] = np.square(x[i])
else:
y[i] = np.power(x[i],4)
print(y)
Since I am handling large arrays and performing this action many times, I am looking for a way to do this without looping over all elements.
Aucun commentaire:
Enregistrer un commentaire