0

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:

enter image description here

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

7
  • Thought I could use the index position of 0 and go from there, then realized I didn't have a 0 value. Ive edited the post to reflect this (thanks to those that also suggested this) Commented Jun 28, 2016 at 0:37
  • 1
    Not clear about the definition. Firstly, shouldn't 1 be the closest value that is close to 0 in the first example; in the second example should you return 0 or 1 -1?; Commented Jun 28, 2016 at 0:45
  • What should be returned in your first example, [2, -2], [-10, 1], or both? Can we assume that the numbers are monotonically decreasing? Commented Jun 28, 2016 at 0:51
  • I need the values of -2 and 2 to be returned where the value of 1 is an anomaly (in the 2nd example I would want 1 and -1). It can't be assumed that the values are monotonically decreasing. Will add a figure Commented Jun 28, 2016 at 1:02
  • Can an anomaly occur at the beginning of the series? Commented Jun 28, 2016 at 1:04

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

It works. Hopefully there are no other scenarios that creep up and break it. I will test it and see

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.