Skip to main content
 首页 » 编程设计

python之NumPy map 计算取决于索引

2024年08月27日32zhengyun_ustc

我有一个形状为 (Height, Width) 的 NumPy 数组。现在我想计算这个数组中存在的所有元素的值。该值是元素位置 [x,y] 的函数。

假设我想为所有元素分配值 (x**2+y**2)/2。我想在不使用 for 循环的情况下执行此操作。有没有办法做到这一点?

请您参考如下方法:

您还可以查看 meshgrid、mgrid 和/或 indices:

>>> H, W = 4,5 
>>> x, y = np.indices([H, W]) 
>>> m 
array([[  0. ,   0.5,   2. ,   4.5,   8. ], 
       [  0.5,   1. ,   2.5,   5. ,   8.5], 
       [  2. ,   2.5,   4. ,   6.5,  10. ], 
       [  4.5,   5. ,   6.5,   9. ,  12.5]]) 

这是有效的,因为 x 和 y 是具有适当的 x 和 y 坐标的数组:

>>> x 
array([[0, 0, 0, 0, 0], 
       [1, 1, 1, 1, 1], 
       [2, 2, 2, 2, 2], 
       [3, 3, 3, 3, 3]]) 
>>> y 
array([[0, 1, 2, 3, 4], 
       [0, 1, 2, 3, 4], 
       [0, 1, 2, 3, 4], 
       [0, 1, 2, 3, 4]]) 

meshgrid 和 mgrid 允许更精细的控制,例如

>>> x, y = np.meshgrid(np.linspace(0, 1, 5), np.linspace(0, 10, 3)) 
>>> x 
array([[ 0.  ,  0.25,  0.5 ,  0.75,  1.  ], 
       [ 0.  ,  0.25,  0.5 ,  0.75,  1.  ], 
       [ 0.  ,  0.25,  0.5 ,  0.75,  1.  ]]) 
>>> y 
array([[  0.,   0.,   0.,   0.,   0.], 
       [  5.,   5.,   5.,   5.,   5.], 
       [ 10.,  10.,  10.,  10.,  10.]])