0
0
NumPydata~5 mins

Indexing with ellipsis in NumPy

Choose your learning style9 modes available
Introduction

Ellipsis helps you select parts of multi-dimensional arrays easily without writing all the colons.

You have a 3D or higher array and want to select all elements in some dimensions but specific ones in others.
You want to avoid typing many colons when slicing arrays with many dimensions.
You want to write cleaner and shorter code when working with big arrays.
You want to select a slice in the last dimension but keep all others.
You want to quickly access data in arrays with unknown or variable number of dimensions.
Syntax
NumPy
array[..., index]
array[index, ...]
array[..., start:end]

The ... means 'all the dimensions I did not specify here'.

You can use ellipsis anywhere in the index, but only once per indexing.

Examples
Selects all rows and columns but only the element at index 1 in the last dimension.
NumPy
import numpy as np
arr = np.arange(27).reshape(3,3,3)
print(arr[..., 1])
Selects all elements in the last two dimensions for the first dimension index 1.
NumPy
print(arr[1, ...])
Selects all elements but only the first two in the last dimension.
NumPy
print(arr[..., :2])
Sample Program

This code creates a 3D array and uses ellipsis to select the last two elements in the last dimension for all other dimensions.

NumPy
import numpy as np

# Create a 3D array with shape (2, 3, 4)
arr = np.arange(24).reshape(2, 3, 4)

# Use ellipsis to select all rows and columns but only the last two elements in the last dimension
result = arr[..., 2:]

print("Original array shape:", arr.shape)
print("Selected slice shape:", result.shape)
print("Selected slice:")
print(result)
OutputSuccess
Important Notes

Ellipsis is very useful when you do not want to write many colons for high-dimensional arrays.

You can only use one ellipsis per indexing operation.

Ellipsis always expands to cover all missing dimensions.

Summary

Ellipsis (...) helps select parts of multi-dimensional arrays easily.

It replaces multiple colons and covers all unspecified dimensions.

Use it to write cleaner and shorter code when slicing arrays.