Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does searchsort in python work?

To make my question clear say if I have an array a as Out[123]: [1, 3, 4, 6, 9, 10, 54] When I try to search the numbers in the list, searchsort returns correct value but when I try something not in the list, it returns an absurd value

here is some of the results

In [131]: a
Out[131]: [1, 3, 4, 6, 9, 10, 54]

In [132]: searchsorted(a,1)
Out[132]: 0

In [133]: searchsorted(a,6)
Out[133]: 3

In [134]: searchsorted(a,[9,54,1])
Out[134]: array([4, 6, 0])

In [135]: searchsorted(a,[9,54,1,0])
Out[135]: array([4, 6, 0, 0])
***> # here 0 is not in the list, but turns up @ position 0***

In [136]: searchsorted(a,740)
Out[136]: 7
***> # here 0 is not in the list, but turns up @ position 7***

why is this happening?

like image 743
Ars3nous Avatar asked Mar 15 '13 06:03

Ars3nous


People also ask

What does Searchsorted do in Python?

searchsorted() function is used to find the indices into a sorted array arr such that, if elements are inserted before the indices, the order of arr would be still preserved. Here, binary search is used to find the required insertion indices.

How do I reverse a NumPy array?

Using flip() function to Reverse a Numpy array The numpy. flip() function reverses the order of array elements along the specified axis, preserving the shape of the array.

What is NP add at?

The add.at a function in NumPy allows you to perform an in-place operation on the left-side operand. In the case of an addition operation, the function will add the right operand to the left operand at the specified array index.


1 Answers

searchsorted tells you where the element belongs to guarantee ordering:

Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.

inserting 740 at position 7 would preserve ordering, as would inserting 0 at position 0.

like image 164
John Lyon Avatar answered Nov 15 '22 22:11

John Lyon