Learning Objectives – after this chapter you will be able to:
  • 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() and argmin().
  • 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
Output
(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
Output
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])
Output
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)
Output
[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))
Output
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, any and all test membership.
Video : Array Search
Question / Answer (15 questions)

Answer : It returns a tuple of arrays containing the indexes of the elements where the condition is True – one array per dimension. For a 1-D array, np.where(cond)[0] gives the index array.

Answer : [0 2 5] – the positions at which the value 4 occurs.

Answer : np.where returns one index array per dimension so that the same function works for arrays of any dimension. A 1-D array has one dimension, so the tuple contains a single array.

Answer : A tuple containing an empty array, e.g. (array([], dtype=int64),); np.where(...)[0] prints [].

Answer : It performs a binary search on a sorted array and returns the index at which a value should be inserted so that the array remains sorted.

Answer : If the value already exists, side="left" (the default) returns the index of its first occurrence, while side="right" returns the index just after its last occurrence. For [10,20,30,40,50] and 30 they return 2 and 3.

Answer : The array must be sorted in ascending order; otherwise the result is not meaningful.

Answer : Yes. Pass a list or array of values, e.g. np.searchsorted(arr, [5, 25, 60]) returns [0 2 5].

Answer : They return the index of the maximum and minimum value respectively. If the extreme value occurs more than once, the index of the first occurrence is returned.

Answer : m.argmax() gives a flat index; convert it with np.unravel_index(m.argmax(), m.shape) to get (row, column).

Answer : Two arrays: the row indexes and the column indexes of the matching elements. For m = [[5,8,2],[9,8,1]] it returns ([0 1], [1 1]).

Answer : np.where returns separate index arrays per dimension; np.argwhere returns a 2-D array where each row is the full index (e.g. [row, column]) of one match.

Answer : The indexes of the non-zero (truthy) elements, as a tuple of arrays like np.where. For [0, 3, 0, 5] it returns positions [1 3].

Answer : Use the in operator (9 in arr), np.isin(values, arr) for several values, or np.any(arr == value).

Answer : Use np.count_nonzero(arr > 5) or (arr > 5).sum(), because True counts as 1.
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.

Q1. np.where(np.array([1, 5, 1]) == 1)[0] returns:

Show Answer

Correct Answer : A. [0 2]
The value 1 is at positions 0 and 2.

Q2. Which function performs a binary search on a sorted array?

Show Answer

Correct Answer : D. np.searchsorted
searchsorted uses binary search to find insertion points.

Q3. np.searchsorted([10, 20, 30], 25) returns:

Show Answer

Correct Answer : B. 2
25 belongs between 20 and 30, at index 2.

Q4. For np.array([3, 9, 9, 1]).argmax(), the result is:

Show Answer

Correct Answer : C. 1
The first occurrence of the maximum (9) is at index 1.

Q5. Which function converts a flat index into (row, column)?

Show Answer

Correct Answer : A. np.unravel_index
np.unravel_index maps a flat index to a multi-dimensional index.

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.

  1. NumPy Developers. (n.d.). numpy.where. NumPy API Reference. https://numpy.org/doc/stable/reference/generated/numpy.where.html
  2. NumPy Developers. (n.d.). Sorting, searching, and counting. NumPy API Reference. https://numpy.org/doc/stable/reference/routines.sort.html
  3. NumPy Developers. (n.d.). Indexing on ndarrays. NumPy User Guide. https://numpy.org/doc/stable/user/basics.indexing.html
  4. NumPy Developers. (n.d.). NumPy quickstart. NumPy User Guide. https://numpy.org/doc/stable/user/quickstart.html
  5. VanderPlas, J. (2016). Python Data Science Handbook. O’Reilly Media. (Free online edition.) https://jakevdp.github.io/PythonDataScienceHandbook/