1

I have a numpy array:

>>> n1 = np.array([[1, 4], [1, 5], [2, 4], [7, 2], [1, 3], [4, 7], [2, 9]])
>>> n1
array([[1, 4],
       [1, 5],
       [2, 4],
       [7, 2],
       [1, 3],
       [4, 7],
       [2, 9]])

I'm looking for a way to find the index of the occurrence of a value in the first column that follows the occurrence of a value greater than it. In this instance, I want:

array([4, 6])

because the value 1 is less than 7, and the value 2 is less than 4 (all in column 0)

Is there a nice Pythonic way of doing this?

3
  • Play with n1[1:,:]-n1[:-1,:], the difference between successive rows. Commented Mar 19, 2018 at 20:09
  • Hi @hpaulj, thanks. By assigning a new array n2 that contains only column 0 of n1, and using your suggestion, I built np.where(n2[1:]-n2[:-1] < 0) which gives me (array([3, 5]),), not array([4, 6]) Commented Mar 19, 2018 at 20:13
  • where gives a tuple, one element per dimension of the condition. Your case is 1d, so the result is a 1 element tuple. Commented Mar 19, 2018 at 20:35

1 Answer 1

1

You could use numpy.diff on the first column and find where values are negative.

np.where(np.diff(n1[:, 0]) < 0)

Add 1 to adjust the index if needed.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @busybear, that gives me (array([3,5]),), which isn't quite what I'm looking for (of course I acknowledge you said to play with 1 to adjust the index)
Are you looking for a solution without needing to add 1? Seems like a trivial step to take.
True. It's a bit pedantic. Still, for anyone who's looking, do this: n2 = np.where(np.diff(n1[:, 0]) < 0), then n3 = np.sum(n2, 1) and it gets you array([4, 6]) as required.

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.