Nathan Thomas - 9 months ago 31

Python Question

I have a numpy array, provided at random, which for this example looks like:

`a = [10, 8, 6, 4, 2, -2, -4, -6, -8, -10, 1]`

ideally, in this example, the values would be between -10 and 10 but this cannot be guaranteed (as above).

I want to retrive the 2 values closest to zero, such that:

`b = a[a > 0][-1]`

c = a[a < 0][0]

which would ideally return me the values of 2 and -2. However, the 1 value is included in the slice in b and i get returned the values of 1 and -2.

Is there a way in numpy to retrieve the values immediately 'next' to zero?

Its worth noting that whilst I always want to split the array at 0, the array could be any length and I could have an uneven number of positive and negative values in the array (i.e. [5, 4, 3, 2, 1, 0, -1])

A real world example is:

I want the yellow and green position but get returned the blue and green position instead, as the data crosses back over zero from -ve to +ve

Answer

This function should do the job:

```
import numpy as np
def my_func(x):
left = np.where(x[:-1]>0)[0][-1]
right = 1 + np.where(x[1:]<0)[0][0]
return x[left], x[right]
```

Demo:

```
>>> a = np.array([10, 8, 6, 4, 2, -2, -4, -6, -8, -10, 1])
>>> b = np.array([5, 4, 3, 2, 1, 0, -1])
>>> my_func(a)
(2, -2)
>>> my_func(b)
(1, -1)
```