I have a function that does this: it takes a given numpy array Aand a given function funcand applies this function to each element of the array.
def transform(A, func):
return func(A)
Aand funcshipped outside, and I have no 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 a normal numpy function, for example. lambdas like it transform(A, lambda x: x^2 if x > 5 else 0). Of course, the second is not vectorized, so I will 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 not want to put this burden on users. I would like to get a unified approach to all functions. I just get the function outside and apply it.
Is there a way to decide which function requires vectorization and which does not? Sort of:
def transform(A, func):
if requires_vectorization(func):
func = np.vectorize(func)
return func(A)
Or do I just need to vectorize everything by default.
def transform(A, func):
func = np.vectorize(func)
return func(A)
Is this a good decision? In other words, won't the call np.vectorizeto an already vectorized function hinder it ? Or is there an alternative?