Most efficient way to map function over numpy array

前端 未结 11 1328
庸人自扰
庸人自扰 2020-11-22 02:13

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          


        
11条回答
  •  旧巷少年郎
    2020-11-22 02:55

    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

提交回复
热议问题