TExcelTAD
Home › NumPy › NumPy Array Search

NumPy Array Search

Searching means finding where in an array certain values are. NumPy's answers are indices, which you can then use to read or change the matching elements.

np.where: positions that match a condition

np.where(condition) returns the indices of all elements where the condition is True. For a 1-D array the result is a tuple with one index array inside:

python · try it yourself
import numpy as np

daily_visitors = np.array([120, 340, 95, 410, 340, 80, 220])
busy = np.where(daily_visitors > 300)
print(busy)
print("busy day indices:", busy[0])
print("their values:    ", daily_visitors[busy])

print("exact matches for 340:", np.where(daily_visitors == 340)[0])
(array([1, 3, 4]),)
busy day indices: [1 3 4]
their values:     [340 410 340]
exact matches for 340: [1 4]

The result is a tuple because NumPy returns one index array per dimension. For a 2-D array you get row indices and column indices:

python · try it yourself
import numpy as np

board = np.array([[0, 5, 0],
                  [7, 0, 5],
                  [5, 0, 0]])
rows, cols = np.where(board == 5)
for r, c in zip(rows, cols):
    print(f"5 found at row {r}, column {c}")

print(np.argwhere(board == 5))    # the same, as (row, col) pairs
5 found at row 0, column 1
5 found at row 1, column 2
5 found at row 2, column 0
[[0 1]
 [1 2]
 [2 0]]

np.where with three arguments: choose values

With three arguments, np.where(condition, x, y) is a vectorised if/else: it builds a new array taking x where the condition holds and y elsewhere.

python · try it yourself
import numpy as np

numbers = np.array([3, 8, 5, 12, 7, 10])
print(np.where(numbers % 2 == 0, "even", "odd"))

prices = np.array([19.0, 45.0, 99.0, 12.0])
discounted = np.where(prices > 40, prices * 0.9, prices)  # 10 % off big items
print(discounted)
['odd' 'even' 'odd' 'even' 'odd' 'even']
[19.  40.5 89.1 12. ]

Searching for the largest or smallest: argmax / argmin

argmax returns the index of the largest value (the first one, if it appears more than once); argmin the smallest:

python · try it yourself
import numpy as np

cities = np.array(["Oslo", "Rome", "Cairo", "Lima"])
temps = np.array([4.0, 18.5, 27.0, 19.0])
hot = temps.argmax()
print(f"Warmest: {cities[hot]} at {temps[hot]} degrees")
print(f"Coldest: {cities[temps.argmin()]}")
Warmest: Cairo at 27.0 degrees
Coldest: Oslo

np.searchsorted: where would a value go?

On a sorted array, np.searchsorted(a, v) uses a binary search to find the index where v would be inserted to keep the order. It is very fast even for millions of elements.

python · try it yourself
import numpy as np

thresholds = np.array([0, 50, 70, 85])      # grade boundaries (sorted)
grades = np.array(["F", "D", "C", "B"])
scores = np.array([45, 70, 91, 85, 12])

# side="right": a score equal to a boundary belongs to the upper grade
idx = np.searchsorted(thresholds, scores, side="right") - 1
print(idx)
print(grades[idx])

print(np.searchsorted([10, 20, 30], 25))          # 25 goes at index 2
print(np.searchsorted([10, 20, 30], 20, side="right"))
[0 2 3 3 0]
['F' 'C' 'B' 'B' 'F']
2
2

By default (side="left"), equal values are inserted before existing ones; with side="right" they go after. Notice how searchsorted turned a long chain of if score >= … tests into one line.

Summary

Function Returns
np.where(cond) tuple of index arrays where cond is True
np.where(cond, x, y) new array mixing x and y
np.argwhere(cond) (n, ndim) array of index rows
np.nonzero(a) same as np.where(a != 0)
a.argmax() / a.argmin() index of the max / min value
np.searchsorted(a, v) insertion index into sorted a

Test yourself

What does np.where(np.array([4, 9, 2, 9]) == 9) return?

  1. (array([1, 3]),)
  2. array([9, 9])
  3. 1
  4. (array([True]),)

What is np.searchsorted([1, 3, 5, 7], 4)?

  1. 1
  2. 2
  3. 3
  4. 4

Which expression replaces negative numbers in a with 0?

  1. np.where(a < 0)
  2. np.where(a < 0, 0, a)
  3. a.argmin()
  4. np.searchsorted(a, 0)