0

Suppose I have a 1D array A,

A = [0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.51, 1.52, 1.6, 2, 3, 4, 5, 6, 7, 8, 9, 10]

and I have a value a = 1.5 and I need to find the smallest index of the entry where the value would fit in the array. In this case it should be 5.

import numpy as np
A = np.array([0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.51, 1.52, 1.6, 2, 3, 4, 5, 6, 7, 8, 9, 10])
a = 1.5
print A[np.where(A >= a >= A)]

I know this would not work but can np.where find such indexes?

3
  • Why not perform a simple search comparing each element with a? Commented May 27, 2015 at 8:29
  • 1
    Is A always sorted? Commented May 27, 2015 at 8:32
  • Yes, it is always sorted. Commented May 27, 2015 at 8:34

4 Answers 4

4

Assuming A is sorted, you can do this in O(log n) time with np.searchsorted (A can be an array or a list):

>>> A = [0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.51, 1.52, 1.6, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> np.searchsorted(A, 1.5)
5
Sign up to request clarification or add additional context in comments.

Comments

1

The bisect module does exactly that (in O(log n) time):

>>> from bisect import bisect_left
>>> bisect_left(A, 1.5)
5

2 Comments

@nxkryptor In that case, you need bisect_left
Since bisect_left is a Python modue, and searchsorted is in numpy, I'm interested to know the speed comparison. Do you know if they're comparable?
1

You're looking basically for the minimum index where the value is greater than or equal to what you're trying to insert.

One way to do that is via a call to min but with the proviso that you need to handle an empty array if the value is beyond the last element:

>>> import numpy as np
>>> A = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 1, 2, 3, 4, 5])

>>> min(np.append(np.where(A >= -1)[0],len(A))
0

>>> min(np.append(np.where(A >= 0)[0],len(A))
0

>>> min(np.append(np.where(A >= 0.01)[0],len(A))
1

>>> min(np.append(np.where(A >= 3.5)[0],len(A))
9

>>> min(np.append(np.where(A >= 999)[0],len(A))
11

In all cases, that gives you the index of the element you need to insert before (or one beyond the highest index if you need to append to the list).

Comments

0

You could use argwhere and min:

np.min(np.argwhere(A==a))

Note this will only work if a is in A.

Comments

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.