Pet*_*ter 123 python performance numpy function vectorization
给定NumPy数组A,将相同函数f应用于每个单元格的最快/最有效的方法是什么?
假设我们将分配给A(I,J)的F(A(I,J)) .
函数f没有二进制输出,因此掩码(ing)操作无济于事.
"明显的"双循环迭代(通过每个单元格)是最优解吗?
blu*_*lub 163
您可以只是向量化该函数,然后在每次需要时将其直接应用于Numpy数组:
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
Run Code Online (Sandbox Code Playgroud)
在向量化时直接指定显式输出类型可能更好:
f = np.vectorize(f, otypes=[np.float])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
111122 次 |
| 最近记录: |