Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

python - 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.

question from:https://stackoverflow.com/questions/65902428/numpy-find-last-less-than-value-index-in-sorted-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...