向量化内的数组索引

时间:2018-07-31 02:20:06

标签: python numpy numpy-broadcasting

有没有办法利用向量化numpy方程中的数组索引?

具体来说,我有这个循环代码,它将2d数组的每个值设置为到某个任意中心点的距离。

img=np.ndarray((size[0],size[1]))
for x in range(size[0]):
    for y in range(size[1]):
        img[x,y]=math.sqrt((x-center[0])**2+(y-center[1])**2)

我该如何将其矢量化?

3 个答案:

答案 0 :(得分:3)

您可以使用广播轻松解决此问题:

import numpy as np

size = (64, 64)
center = (32, 32)

x = np.arange(size[0])
y = np.arange(size[1])

img = np.sqrt((x - center[0]) ** 2 + (y[:, None] - center[1]) ** 2)

答案 1 :(得分:1)

熊猫提供的一些帮助会使此任务相对容易:

=IF(IF(OR(AND(B2>=$G$2,B2<=$H$2),AND(C2>=$G$2,C2<=$H$2)),$F$2,"")&IF(OR(AND(B2>=$G$3,B2<=$H$3),AND(C2>=$G$3,C2<=$H$3)),$F$3,"")<>"",IF(OR(AND(B2>=$G$2,B2<=$H$2),AND(C2>=$G$2,C2<=$H$2)),$F$2&IF(OR(AND(B2>=$G$3,B2<=$H$3),AND(C2>=$G$3,C2<=$H$3))=TRUE," & ",""),"")&IF(OR(AND(B2>=$G$3,B2<=$H$3),AND(C2>=$G$3,C2<=$H$3)),$F$3,""),"<Null>")

答案 2 :(得分:0)

是的,有。

import numpy as np

size = (6, 4)
center = (3, 2)
img_xy = np.array([[(x, y) for x in range(size[0])] for y in range(size[1])])

img = np.sum((img_xy - center) ** 2, axis=2) ** 0.5
print('\nPlan1:\n', img)

img = np.linalg.norm(img_xy - center, axis=2)
print('\nPlan2:\n', img)

您将获得:

Plan1:
 [[3.60555128 2.82842712 2.23606798 2.         2.23606798 2.82842712]
 [3.16227766 2.23606798 1.41421356 1.         1.41421356 2.23606798]
 [3.         2.         1.         0.         1.         2.        ]
 [3.16227766 2.23606798 1.41421356 1.         1.41421356 2.23606798]]

Plan2:
 [[3.60555128 2.82842712 2.23606798 2.         2.23606798 2.82842712]
 [3.16227766 2.23606798 1.41421356 1.         1.41421356 2.23606798]
 [3.         2.         1.         0.         1.         2.        ]
 [3.16227766 2.23606798 1.41421356 1.         1.41421356 2.23606798]]

如果有任何疑问,可以问我。