0

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.

1
  • 1
    Can't you do something like this print([np.searchsorted(arr, x, side='right')-1 for x in vs]) Commented Jan 26, 2021 at 13:52

1 Answer 1

1

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

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

array([0, 1, 3], dtype=int64)
Sign up to request clarification or add additional context in comments.

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.