2
我還有一個關於NumPy的問題)由索引條件numpy陣列修改
我想從條件選擇一些節點從網格節點。目的是取最接近圓的節點,並將它們移動到圓邊界(由Ox或Oy決定 - 它取決於距離會更小)。
我的實現:有趣節點
for i, val in np.ndenumerate(X[condition]):
pass
for j, val in np.ndenumerate(Y[condition]):
pass
那我應該比較X和Y(即我需要的
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)座標值而不是索引),並根據比較結果修改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]
對不起誤導 - 我應該從節點沒有座標,但距離比較圓邊界由Ox/Oy(我編輯了這個問題)。 – erthalion
仍然以同樣的方式工作;只需使用'distance_X
ecatmur
謝謝,你說得對。但有一個時刻,我仍然不明白 - 我怎樣才能使用這個操作 'X [condition&condition2] = val' 設定值,這將取決於指數? 'X [condition&condition2] = func(index)' – erthalion