是否有一个相当于 python map 的 numpy 函数

扎眼的阳光 python 531

原文标题is there a numpy function that equivalent to python map

我有一个包含 n 个 2d 数组的 3d 数组,无论如何我可以将每个 2d 数组映射到某个值,而无需使用 python 映射中的 bulit 或 for 循环(我被要求不使用它)仅使用 numpy 函数。

例如我想做这样的事情:

def map2d_arr(arr2d): #this is for the exampe only can be any condition on the 2d array
    return sum(arr2d) > 10;

a = np.arange(27).reshape((3,3,3))
res = np.map(map2d_arr,a) # how to do something like that only in numpy
                          #should return boolean array 

有 np.vectorize 和沿轴但它们不采用完整的二维数组

原文链接:https://stackoverflow.com//questions/71910102/is-there-a-numpy-function-that-equivalent-to-python-map

回复

我来回复
  • Peter Hassaballah的头像
    Peter Hassaballah 评论

    不,但是您可以轻松地创建一个 lambda 函数来实现该目的。

    
    list = np.array([1, 2, 3, 4])
    
    #define function
    my_function = lambda x: x*2
    
    #apply function to NumPy array
    my_function(list)
    
    #Result : list = [2, 4, 6, 8]
    

    希望这有帮助!

    2年前 0条评论