首页 文章

在NumPy阵列的每个单元处有效地评估函数

提问于
浏览
113

给定NumPy数组A,将 same 函数f应用于 every cell的最快/最有效的方法是什么?

  • 假设我们将分配给A(i,j)f(A(i,j)) .

  • 函数,f,没有't have a binary output, thus the mask(ing) operations won' t帮助 .

“明显的”双循环迭代(通过每个单元格)是最优解吗?

3 回答

  • 4

    您可以只使用vectorize函数,然后在每次需要时将其直接应用于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
    

    在向量化时直接指定显式输出类型可能更好:

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

    类似的问题是:Mapping a NumPy array in place . 如果你能找到f()的ufunc,那么你应该使用out参数 .

  • 1

    如果您正在处理数字和 f(A(i,j)) = f(A(j,i)) ,则可以使用scipy.spatial.distance.cdist将f定义为 A(i)A(j) 之间的距离 .

相关问题