user3396592 - 1 year ago 113

Python Question

So I have a numpy array of tuples and I want to remove all tuples where the first value is less than 0 or the second element is greater than a number, n.

So if n = 10 and we had this array:

`[[-1, 5], [3, 11], [-4, 20]]`

It would become this:

`[[]]`

I'm guessing I need to use

`np.delete`

`np.where`

Thanks in advance.

Answer Source

You can solve this using logical indexing. I'm guessing in your example you meant that

```
[[-1, 5], [3, 11], [-4, 20]]
```

would become

```
[]
```

Since you said that the conditions are:

I want to

removeall tuples where thefirst value is less than 0orthesecond element is greater than a number, n.

```
>>> import numpy as np
>>> arr = np.array([[-1, 5], [3, 11], [-4, 20]])
>>> arr[~((arr[:,0] < 0) | (arr[:,1] > 10))]
array([], shape=(0, 2), dtype=int64)
```

Basically it's all down to expressing your logical requirement as the combination (through `|`

and `&`

) of different logical masks.

The `~`

takes the inverse of the mask, since you said you wanted to **delete** elements that match your criteria. A better example of this method working is this:

```
>>> import numpy as np
>>> arr = np.array([[-1, 5], [1, 1], [3, 11], [-4, 20], [2, 9]])
>>> arr[~((arr[:,0] < 0) | (arr[:,1] > 10))]
array([[1, 1], [2, 9]])
```