Untouched Descending Search Sorter

I am trying to figure out how to use numpy.searchsorted correctly to find the correct index where an element needs to be inserted. When I run the following:

e = np.array([9,8,7,6])
np.searchsorted(e,5)

      

The output I get is 0, which is not correct as I would expect 4 as an answer. Is the search sorted for arrays in descending order? What options do I have if I need to store the array in descending order? Many thanks!

+3


source to share


3 answers


You can search the reverse array and then reverse the index later:

e = np.array([9,8,7,6])
e.size - np.searchsorted(e[::-1], 5, side = "right")
# 4

      



Note that the parameter side

here must be opposite to directly search the original array if you want the result to be consistent.

+5


source


As described in the documentation :

numpy.searchsorted(a, v, side='left', sorter=None)

Find the indices at which elements must be inserted to maintain order.

Find indices in sorted array a such that if the corresponding elements in v

were inserted before the indices, the order of a is preserved.

Parameters:

  • a

    : 1-D array_like

    Input array. If sorter

    - None

    , then it must be sorted in ascending order , otherwise the sorter must be an array of indices that sort it.

(...)

(added formatting)

So, you need to provide an array sorted in ascending order.



However, it's easy to solve this problem for numeric data : you just use negation:

e = np.array([9,8,7,6])
np.searchsorted(-e,-5)
#               ^  ^
      

You can also use an inverse array (for non-numeric data, for example) as suggested by @Psidom .

+4


source


You can do this using an optional argument sorter

. According to the documentation, this is usually the result of np.argsort(e)

:

array([3, 2, 1, 0])

      

What can you do more efficiently this way:

np.arange(len(e)-1, -1, -1)

      

Then:

np.searchsorted(e, 7.5, sorter=np.arange(len(e)-1, -1, -1))

      

Gives you 2.

+1


source







All Articles