ThunderFlashxShanuLover - 1 year ago 74

Python Question

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`

`y1`

`x1`

`y1`

`x1`

`y1`

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

to get an array like

`([[x1, y1], [x2, y2], [x3, y3],...]])`

Thanks.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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)
```