在NumPy数组的每个单元格上有效评估函数 [英] Efficient evaluation of a function at every cell of a NumPy array

查看:111
本文介绍了在NumPy数组的每个单元格上有效评估函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定 NumPy 数组 A ,最快/将相同函数 应用于每个单元格的最有效方法?


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


  2. 函数 f 没有二进制输出,因此mask(ing)操作不会起作用。


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

    解决方案

    您可以向量化函数,然后在每次需要时将其直接应用于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)#或者如果您想保留原始的f

    result_array = f(A) #如果A是你的Numpy数组

    最好在向量化时直接指定显式的输出类型:

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


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

    1. Suppose that we will assign to A(i,j) the f(A(i,j)).

    2. The function, f, doesn't have a binary output, thus the mask(ing) operations won't help.

    Is the "obvious" double loop iteration (through every cell) the optimal solution?

    解决方案

    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])
    

    这篇关于在NumPy数组的每个单元格上有效评估函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆