Efficient evaluation of a function at every cell of a NumPy array

后端 未结 6 2270
一整个雨季
一整个雨季 2020-11-28 03:20

Given a NumPy array A, what is the fastest/most efficient way to apply the same function, f, to every cell?

6条回答
  •  清歌不尽
    2020-11-28 03:47

    You could just vectorize the function and then apply it directly to a Numpy array each time you need it:

    import numpy as np
    
    def f(x):
        return x * x + 3 * x - 2 if x > 0 else x * 5 + 8
    
    f = np.vectorize(f)  # or use a different name if you want to keep the original f
    
    result_array = f(A)  # if A is your Numpy array
    

    It's probably better to specify an explicit output type directly when vectorizing:

    f = np.vectorize(f, otypes=[np.float])
    

提交回复
热议问题