- Find the indexes of matching values with
np.where(). - Find insertion positions in a sorted array with
np.searchsorted(). - Locate the largest and smallest values with
argmax()andargmin(). - Search 2-D arrays and test whether values exist.
Searching with np.where()
np.where(condition) returns the indexes where the condition is True, as a tuple of arrays (one array per dimension). Use [0] to get the index array of a 1-D array.
import numpy as np arr = np.array([4, 7, 4, 9, 2, 4]) result = np.where(arr == 4) print(result) print(result[0]) print(np.where(arr % 2 == 0)[0]) # positions of even numbers print(np.where(arr > 10)[0]) # no match -> empty array
(array([0, 2, 5]),) [0 2 5] [0 2 4 5] []
np.searchsorted()
np.searchsorted(sorted_arr, value) performs a binary search on a sorted array and returns the index where value should be inserted to keep the order. By default it searches from the left; side="right" searches from the right.
import numpy as np arr = np.array([10, 20, 30, 40, 50]) print(np.searchsorted(arr, 35)) print(np.searchsorted(arr, 30)) # left side print(np.searchsorted(arr, 30, side="right")) print(np.searchsorted(arr, [5, 25, 60])) # many values
3 2 3 [0 2 5]
searchsorted() assumes the array is already sorted in ascending order. On an unsorted array the result is meaningless.argmax(), argmin() and nonzero()
import numpy as np
sales = np.array([120, 340, 90, 340, 210])
print("Best day index :", sales.argmax()) # first occurrence of max
print("Worst day index:", sales.argmin())
print("Non-zero positions:", np.nonzero(np.array([0, 3, 0, 5]))[0])Best day index : 1 Worst day index: 2 Non-zero positions: [1 3]
Searching a 2-D Array
For 2-D arrays np.where() returns two arrays: row indexes and column indexes. np.argwhere() returns them as (row, column) pairs.
import numpy as np
m = np.array([[5, 8, 2],
[9, 8, 1]])
rows, cols = np.where(m == 8)
print(rows, cols)
print(np.argwhere(m > 6))
r, c = np.unravel_index(m.argmax(), m.shape) # position of the maximum
print("Max at row", r, "column", c)[0 1] [1 1] [[0 1] [1 0] [1 1]] Max at row 1 column 0
Checking Whether Values Exist
import numpy as np arr = np.array([3, 6, 9, 12]) print(9 in arr, 5 in arr) print(np.isin([6, 7], arr)) print(np.any(arr > 10), np.all(arr > 0)) print(np.count_nonzero(arr > 5))
True False [ True False] True True 3
Key Takeaways
np.where(cond)returns a tuple of index arrays; use[0]for 1-D.searchsorted()needs a sorted array and returns insertion positions.argmax()/argmin()find positions of extremes;isin,anyandalltest membership.
Video : Array Search
Question / Answer (15 questions)
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.
- NumPy Developers. (n.d.). numpy.where. NumPy API Reference. https://numpy.org/doc/stable/reference/generated/numpy.where.html
- NumPy Developers. (n.d.). Sorting, searching, and counting. NumPy API Reference. https://numpy.org/doc/stable/reference/routines.sort.html
- NumPy Developers. (n.d.). Indexing on ndarrays. NumPy User Guide. https://numpy.org/doc/stable/user/basics.indexing.html
- NumPy Developers. (n.d.). NumPy quickstart. NumPy User Guide. https://numpy.org/doc/stable/user/quickstart.html
- VanderPlas, J. (2016). Python Data Science Handbook. O’Reilly Media. (Free online edition.) https://jakevdp.github.io/PythonDataScienceHandbook/