roger
roger

Reputation: 9943

numpy find last less than value index in sorted array?

I have a exactly sorted numpy array like this:

arr = np.asarray([1351.1, 1351.11, 1351.14, 1351.16])

and I have a value array also exactly sorted value like this:

vs = np.asarray([1351.10, 1351.13, 1351.17])

I want to find the last index of value in arr is less than or equal to vs, for example:

  1. vs[0]=1351.10 => arr[0] == v[0] => output 0
  2. vs[1]=1351.13 => arr[1] < v[1] and arr[2] > v[1] => output 1
  3. vs[2]=1351.17 => arr[3] < v[2] => output 3

so at last output [0, 1, 3]

Of course I can for loop arr, then compare arr with vs, but if arr size is very big, it maybe not a good option.

And I find np.searchsorted, it is not what my want, for example: np.searchsorted(arr, 1351.13) returns 2, but I want to 1. And also another question, it cannot make use of vs is also sorted.

Upvotes: 0

Views: 619

Answers (1)

Daniel F
Daniel F

Reputation: 14399

Just use np.searchsorted with side = 'right' and then subtract 1:

np.searchsorted(arr, vs, side = 'right') - 1

array([0, 1, 3], dtype=int64)

Upvotes: 1

Related Questions