What is the most efficient way to map a function over a numpy array? The way I\'ve been doing it in my current project is as follows:
import numpy as np
x
It seems no one has mentioned a built-in factory method of producing ufunc
in numpy package: np.frompyfunc
which I have tested again np.vectorize
and have outperformed it by about 20~30%. Of course it will perform well as prescribed C code or even numba
(which I have not tested), but it can a better alternative than np.vectorize
f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)
%timeit f_arr(arr, arr) # 307ms
%timeit vf(arr, arr) # 450ms
I have also tested larger samples, and the improvement is proportional. See the documentation also here