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!
source to share
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_likeInput 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 .
source to share
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.
source to share