ThunderFlashxShanuLover ThunderFlashxShanuLover - 4 months ago 9
Python Question

Removing entries from arrays in a parallel manner

I have a list/array of x and y coordinates, for example:

x = [x1, x2, x3,...]
y = [y1, y2, y3,...]


Now, I want to remove certain entries based on conditions, for example, the following,

for i in x1:
if i <= 40 and i >= -40:
print "True"
else:
x.remove(i)

for i in y1:
if i <= 20 and i >=- 20:
print "True"
else:
y1.remove(i)


The code above removes the respective entries from the lists, but if
x1
is removed,
y1
still remains in the list. What I want to achieve is, if
x1
is removed,
y1
should also be removed. How can I go about doing this? My final goal is to try to plot
x1
and
y1
, so I am unable to do this as the lists end up having different dimensions. I can also use

zeta_list = np.column_stack((x1, y1))


to get an array like
([[x1, y1], [x2, y2], [x3, y3],...]])
, but I am not sure how to remove entries from this using an if conditional.

Thanks.

Answer

Form a boolean selection mask:

mask = ~((x > 40) | (x < -40) | (y > 20) | (y < -20))

then, to select values from x and y where mask is True:

x, y = x[mask], y[mask]

When x is a NumPy array, (x > 40) returns a boolean array of the same shape as x which is True where the elements of x are greater than 40.

Note the use of | for bitwise-or and ~ for not (boolean negation).


Alternatively, by De Morgan's law, you could use

mask = ((x <= 40) & (x >= -40) & (y <= 20) & (y >= -20))

NumPy operations are performed element-wise. So mask is True whereever an element of x is between -40 and 40 and the corresponding element of y is between -20 and 20.


For example,

import numpy as np
x = [-50, -50, 30, 0, 50]
y = [-30, 0, 10, 30, 40]

# change the lists to NumPy arrays
x, y = np.asarray(x), np.asarray(y)
# mask = ~((x > 40) | (x < -40) | (y > 20) | (y < -20))
mask = ((x <= 40) & (x >= -40) & (y <= 20) & (y >= -20))
x, y = x[mask], y[mask]

yields

In [35]: x
Out[35]: array([30])

In [36]: y
Out[36]: array([10])

with

In [37]: mask
Out[37]: array([False, False,  True, False, False], dtype=bool)