Elementwise if elif function in python using arrays Elementwise if elif function in python using arrays arrays arrays

Elementwise if elif function in python using arrays


You could use np.where:

def myfunc(a, b):    return np.where(a < b*10, a*2, -a)    

For example,

In [48]: a = np.array([1, 5, 50, 500])In [49]: b = 1In [50]: myfunc(a, b)Out[50]: array([   2,   10,  -50, -500])

Note the output is not the same as your desired output, but is consistent with the code you posted. You can of course get the desired output by reversing the inequality:

def myfunc(a, b):    return np.where(a > b*10, a*2, -a)

then

In [52]: myfunc(a, b)Out[52]: array([  -1,   -5,  100, 1000])


Use a list comprehension:

myarray = [1, 5, 50, 500]b = 1[myfunc(a, b) for a in myarray]


Your function is simple enough that it can be dropped entirely:

arr = [1, 5, 50, 500]arr = [a * 2 if a < b * 10 else -a for a in arr]