I have a function which does this: it takes a given numpy array A
and a given function func
and applies the function to each element of the array.
def transform(A, func):
return func(A)
A
and func
are supplied from outside and I do not have control over them. I would like the functions to work if they are vectorized functions such as transform(A, np.sin)
but I also want to be able to accept normal numpy function e.g. lambdas like transform(A, lambda x: x^2 if x > 5 else 0)
. Of course the second is not vectorized so I would need to call np.vectorize()
before applying it. Like this: transform(A, np.vectorize(lambda x: x^2 if x > 5 else 0))
... But I do nto want to impose this burden on the users. I would like a unified approach to all functions. I just get a function from outside and apply it.
Is there a method to decide which function requires vectorization and which does not? Something like:
def transform(A, func):
if requires_vectorization(func): # how to do this???
func = np.vectorize(func)
return func(A)
Or should I just vectorize all by default
def transform(A, func):
func = np.vectorize(func) # is this correct and efficient?
return func(A)
Is this solution good? In other words, does it hurt to call np.vectorize
on already vectorized function? Or is there any alternative?