Skip to content

NumPy - Indexing & Slicing

Elements within NumPy ndarray objects can be accessed and modified using indexing and slicing, much like standard Python sequences (e.g., lists, tuples).

As previously mentioned, ndarray items use zero-based indexing. NumPy offers several indexing methods, including basic slicing, advanced indexing (integer and boolean), and field access for structured arrays.

Basic slicing extends Python’s slicing concept to multiple dimensions. You can create a slice using the slice(start, stop, step) object or, more commonly, the start:stop:step syntax directly within square brackets [].

Important Note: Basic slicing typically returns a view of the original array, not a copy. Modifying the slice will modify the original array. If you need a copy, use the .copy() method on the slice (e.g., a[start:stop:step].copy()).

Demonstrates creating a slice object and applying it to an array.

import numpy as np
a = np.arange(10) # Creates an array [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = slice(2, 7, 2) # Represents indices from 2 up to (but not including) 7, with a step of 2
print(a[s])

Output:

[2 4 6]

In this example, np.arange(10) creates a 1D array. A slice object s is defined to select elements starting at index 2, ending before index 7, with a step of 2. Applying this slice a[s] extracts the corresponding elements.

The same result is achieved more concisely using the colon notation directly within the brackets.

Demonstrates the standard start:stop:step syntax.

import numpy as np
a = np.arange(10)
b = a[2:7:2] # Equivalent to the slice object in Example 1
print(b)

Output:

[2 4 6]

Omitting slice parameters uses defaults: omitting start defaults to 0, omitting stop defaults to the end of the array, and omitting step defaults to 1. A single index retrieves a single item. A colon : by itself selects the entire dimension.

Accessing a single element by its index.

import numpy as np
a = np.arange(10)
b = a[5] # Access the element at index 5
print(b)

Output:

5

Example 4: Slicing from an index to the end

Section titled “Example 4: Slicing from an index to the end”

Using start: selects all elements from the start index onwards.

import numpy as np
a = np.arange(10)
print(a[2:]) # Elements from index 2 to the end

Output:

[2 3 4 5 6 7 8 9]

Using start:stop selects elements between the specified indices (excluding the stop index).

import numpy as np
a = np.arange(10)
print(a[2:5]) # Elements from index 2 up to (not including) index 5

Output:

[2 3 4]

These slicing concepts extend naturally to multi-dimensional arrays by providing slices for each dimension, separated by commas.

Example 6: Slicing multi-dimensional arrays

Section titled “Example 6: Slicing multi-dimensional arrays”

Applying slicing to a 2D array.

import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print("Original array:")
print(a)
# Slice rows starting from index 1 (the second row)
print('\nSlice from row index 1 onwards (a[1:]):')
print(a[1:])
# Slice a specific region: rows 0 to 1, columns 1 to 2
print('\nSlice rows 0:2, columns 1:3 (a[0:2, 1:3]):')
print(a[0:2, 1:3])

Output:

Original array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Slice from row index 1 onwards (a[1:]):
[[4 5 6]
[7 8 9]]
Slice rows 0:2, columns 1:3 (a[0:2, 1:3]):
[[2 3]
[5 6]]

Slicing can also include ellipsis (...). The ellipsis expands to represent as many colons : as needed to fill the dimensions. It’s useful when dealing with arrays of unknown or high dimensionality.

Demonstrating ellipsis for selecting columns or rows.

import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print('Original array:')
print(a)
print('\n')
# Select all items in the second column (index 1)
# a[..., 1] is equivalent to a[:, 1]
print('Items in the second column (a[..., 1]):')
print(a[..., 1])
print('\n')
# Select all items in the second row (index 1)
# a[1, ...] is equivalent to a[1, :]
print('Items in the second row (a[1, ...]):')
print(a[1, ...])
print('\n')
# Select all items from the second column onwards
# a[..., 1:] is equivalent to a[:, 1:]
print('Items from column index 1 onwards (a[..., 1:]):')
print(a[..., 1:])

Output:

Original array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Items in the second column (a[..., 1]):
[2 5 8]
Items in the second row (a[1, ...]):
[4 5 6]
Items from column index 1 onwards (a[..., 1:]):
[[2 3]
[5 6]
[8 9]]