Skip to main content
Documents
basicsArray CreationArray OperationsArray Computation & AnalysisLinear AlgebraRandom ProbabilityData Input/Output & Conversion

NumPy Array Indexing

NumPy array indexing allows you to access and manipulate individual elements or groups of elements within an array. It provides powerful and flexible tools for selecting, modifying, and analyzing array data efficiently.

Usage

NumPy array indexing is used to extract or modify elements in an array based on their indices. It is essential for tasks like data slicing, filtering, and transformation, and can be performed using integer, boolean, or slice indices.

import numpy as np

# Basic syntax
array[index]
array[start:stop:step]

In this syntax, array[index] accesses a single element, while array[start:stop:step] is used for slicing, allowing you to select a range of elements.

Examples

1. Accessing a Single Element

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(arr[2])

This example accesses the element at index 2 in a one-dimensional array, which is 30.

2. Slicing a One-Dimensional Array

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4])

Here, a slice of the array is obtained from index 1 to 3, resulting in [20, 30, 40].

3. Indexing a Multi-Dimensional Array

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[1, 2])

This example accesses an element in a two-dimensional array, specifically the element in row 1, column 2, which is 6.

4. Boolean Indexing

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(arr[arr > 25])

This example uses boolean indexing to filter elements greater than 25, resulting in [30, 40, 50].

5. Using Ellipsis for Higher Dimensions

import numpy as np

arr = np.arange(27).reshape(3, 3, 3)
print(arr[..., 1])

This demonstrates the use of Ellipsis (...) to select all elements in the last dimension at index 1.

Tips and Best Practices

  • Use slicing over loops. Slicing is generally more efficient than iterating over array elements manually.
  • Understand zero-based indexing. Remember that NumPy uses zero-based indexing, so the first element is at index 0.
  • Use advanced indexing cautiously. While powerful, advanced indexing can lead to unintended data copies; use it wisely to maintain performance.
  • Combine with boolean indexing. Use boolean conditions to filter and index arrays for more dynamic data selection.
  • Beware of negative indices. Negative indices count from the end of the array, which can sometimes lead to unexpected behavior if not used carefully.
  • Consider start and stop indices. In slicing, if the stop index is smaller than the start index, the result is an empty array, which may not be intended.