由索引修改条件numpy数组

时间:2013-07-29 14:46:28

标签: python numpy

我还有一个关于NumPy的问题)

我想按条件从网格中选择一些节点。目的是获取最接近圆的节点,并将它们移动到圆边界(通过Ox或Oy - 它取决于距离更小的距离)。

我的实施:

x = np.linspace(0, lx, nx)
y = np.linspace(0, ly, ny)
X, Y = np.meshgrid(x, y)

# one part of condition
distance = R - np.sqrt((X-x0)**2 + (Y-y0)**2)
condition = (distance > 0) & (distance < step)

现在我可以得到有趣节点的(x,y)坐标

for i, val in np.ndenumerate(X[condition]):
    pass

for j, val in np.ndenumerate(Y[condition]):
    pass

然后我应该比较结果节点的x和y(即我需要值,而不是索引),并根据比较结果修改X或Y. 它可能像:

# distance_X/distance_Y are the distances to circle boundary by Ox/Oy
for x, y in np.nditer([distance_X[condition], distance_Y[condition]]):
    if x < y:
        # modify X array
    if y < x:
        # modify Y array

如您所见,我不能只X[condition] = some_value

那么我该如何实现呢?

UPD:

完整的表述和@ecatmur的建议解决了我的问题。解决方案可能类似于(类似于Y):

condition_X = condition & (distance_X < distance_Y)
X[condition_X] = (X - distance_X)[condition_X]

1 个答案:

答案 0 :(得分:1)

将您的条件与&运算符结合使用:

X[condition & (distance_X < distance_Y)] = ...
Y[condition & (distance_Y < distance_X)] = ...
相关问题