Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional numpy array modification by the indices

Tags:

python

numpy

I have one more question about NumPy)

I want select the some number of the nodes from grid by condition. The purpose is take the nodes that will be closest to circle, and move them to circle boundary (by Ox or Oy - it depends on what distance will be less).

My implementation:

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)

Now I can get (x, y) coordinates of interesting nodes

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

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

Then I should compare x and y (i.e. I need values, not indices) for the resulting nodes, and modify X or Y depending on the result of comparison. It may be like:

# 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

As you see, I can't just X[condition] = some_value

So how can I implement this?

UPD:

The complete formulation and the advice of @ecatmur have solved my problem. The solution may be like (similarly for Y):

condition_X = condition & (distance_X < distance_Y)
X[condition_X] = (X - distance_X)[condition_X]
like image 669
erthalion Avatar asked May 22 '26 02:05

erthalion


1 Answers

Combine your conditions with the & operator:

X[condition & (distance_X < distance_Y)] = ...
Y[condition & (distance_Y < distance_X)] = ...
like image 54
ecatmur Avatar answered May 24 '26 15:05

ecatmur