0
0
NumpyHow-ToBeginner ยท 3 min read

How to Find Index of Value in NumPy Arrays

Use numpy.where() to find the index of a value in a NumPy array. It returns the indices where the condition is true, which you can convert to a list or array for easy use.
๐Ÿ“

Syntax

The basic syntax to find the index of a value in a NumPy array is:

  • numpy.where(condition): Returns indices where the condition is true.
  • condition: A boolean expression, for example, array == value.
python
np.where(array == value)
๐Ÿ’ป

Example

This example shows how to find the index of the value 5 in a NumPy array.

python
import numpy as np

array = np.array([1, 3, 5, 7, 5, 9])
indices = np.where(array == 5)
print(indices)  # Tuple of arrays
print(indices[0])  # Array of indices

# To get a list of indices
index_list = indices[0].tolist()
print(index_list)
Output
(array([2, 4]),) [2 4] [2, 4]
โš ๏ธ

Common Pitfalls

One common mistake is expecting numpy.where() to return a single integer index when multiple matches exist. It returns a tuple of arrays for all matching indices. Also, using list.index() on a NumPy array will cause errors because NumPy arrays do not support this method.

Always use numpy.where() for NumPy arrays instead of Python list methods.

python
import numpy as np

array = np.array([1, 2, 3, 2, 4])

# Wrong: Using list method on numpy array
# index = array.index(2)  # This will raise an AttributeError

# Right: Using numpy.where
indices = np.where(array == 2)
print(indices[0])
Output
[1 3]
๐Ÿ“Š

Quick Reference

Summary tips for finding indices in NumPy arrays:

  • Use np.where(array == value) to get all indices of value.
  • Access the first element of the tuple to get the array of indices: np.where(...)[0].
  • Convert to list if needed with .tolist().
  • For the first occurrence only, use np.argmax(array == value) but check if the value exists.
โœ…

Key Takeaways

Use numpy.where(array == value) to find all indices of a value in a NumPy array.
numpy.where returns a tuple of arrays; use the first element to get the indices array.
Do not use list methods like index() on NumPy arrays; they will cause errors.
Convert indices to a list with .tolist() if you need a Python list.
For the first match only, consider np.argmax but verify the value exists to avoid errors.