Home > other >  Evaluate scalar function on numpy array with conditionals
Evaluate scalar function on numpy array with conditionals

Time:01-17

I have a numpy array r and I need to evaluate a scalar function, let's say np.sqrt(1-x**2) on each element x of this array. However, I want to return the value of the function as zero, whenever x>1, and the value of the function on x otherwise. The final result should be a numpy array of scalars.

How could I write this the most pythonic way?

CodePudding user response:

You can use like numpy.where(condition,if condition holds,otherwise) so np.where(x>1,0,np.sqrt(1-x**2)) will be answer

CodePudding user response:

y = np.where(
   r>1, #if r[i]>1:
   0, #y[i]=0
   np.sqrt(1-r**2) #else: y[i] = (1-r[i]**2)
)

CodePudding user response:

Another way with list comp:

import numpy as np
r=np.array([1,4,2,0.5,0.2])  #dummy r values

np.array([0 if x>1 else np.sqrt(1-x**2) for x in r])
#array([0.       , 0.       , 0.       , 0.8660254, 0.9797959])
  • Related