In python, is there an easy and efficient way to make function f(x: float) accept both lists and numpy arrays as arguments (in which case I would want to apply f element-wise and return the result in the same format as it was sent in)?
For now, I need only 1-dimensional arrays.
As an illustration (my real f is more complex), let's say that I have:
def f(x):
return math.log(x) if x > 0 else 0.0
Then this one works, but is not that elegant - and possibly not that efficient either, because of the recursion (which I use as it allows me to have just one function):
def f(x):
if np.isscalar(x):
return math.log(x) if x > 0 else 0.0
elif isinstance(x, np.ndarray):
return np.array([f(i) for i in x], dtype=float)
else:
return [f(i) for i in x]
Is there a better way?
np.vectorizeandnp.frompyfunc.