NumPy Array Search
Learn all about NumPy Array Search in this comprehensive tutorial.
- •You can search an array for a certain value, and return the indexes that get a match.
- •There is a method called searchsorted() which performs a binary search in the array, and returns the index where the specified value would be inserted to maintain the search order.
Searching Arrays
You can search an array for a certain value, and return the indexes that get a match.
To search an array, use the where() method.
The example above will return a tuple: (array([3, 5, 6],)
Which means that the value 4 is present at index 3, 5, and 6.
Search Sorted
There is a method called searchsorted() which performs a binary search in the array, and returns the index where the specified value would be inserted to maintain the search order.
Example explained: The number 7 should be inserted on index 1 to remain the sort order.
The method starts the search from the left and returns the first index where the number 7 is no longer larger than the next value.
By default the left most index is returned, but we can give side='right' to return the right most index instead.
Example explained: The number 7 should be inserted on index 2 to remain the sort order.
The method starts the search from the right and returns the first index where the number 7 is no longer less than the next value.
To search for more than one value, use an array with the specified values.
The return value is an array: [1 2 3] containing the three indexes where 2, 4, 6 would be inserted in the original array to maintain the order.
Module quiz
2 questionsWhich of the following is true about NumPy Array Search?
What is the most common pitfall when working with NumPy Array Search?
Answer all questions to submit.