What is efficient (speed) way to apply Piecewise functions on Numpy Array?
Say, for example, Piecewise functions are like
For (1) : x<=2 f(x) = 2*x + x^2
(2) : x>2 f(x) = -(x^2 + 2)
Here's what I did.
data = np.random.random_integers(5, size=(5,6))
print data
np.piecewise(data, [data <= 2, data > 2],
[lambda x: 2*x + pow(2, x),
lambda x: -(pow(x, 2) + 2)])
data =
[[4 2 1 1 5 3]
[4 3 3 5 4 5]
[3 2 4 2 5 3]
[2 5 4 3 1 4]
[5 3 3 5 5 5]]
output =
array([[-18, 8, 4, 4, -27, -11],
[-18, -11, -11, -27, -18, -27],
[-11, 8, -18, 8, -27, -11],
[ 8, -27, -18, -11, 4, -18],
[-27, -11, -11, -27, -27, -27]])
Is there an efficient method to go by for smaller arrays, large arrays, many functions etc? My concern is with lambda functions being used. Not sure if these are Numpy optimized.