0
0
NumPydata~5 mins

Multi-dimensional fancy indexing in NumPy

Choose your learning style9 modes available
Introduction

Multi-dimensional fancy indexing helps you pick specific elements from a grid or table using lists of positions. It makes selecting data easy and flexible.

You want to select specific cells from a 2D table based on row and column lists.
You need to extract multiple points from a 3D array using coordinate lists.
You want to rearrange or duplicate parts of a matrix by choosing indexes in any order.
You are working with images and want to pick pixels at certain positions.
You want to quickly gather data points from a dataset stored in a multi-dimensional array.
Syntax
NumPy
array[row_indices, column_indices]

Both row_indices and column_indices can be lists or arrays of integers.

The shapes of the index arrays must match to select elements element-wise.

Examples
Selects elements at positions (0,2), (1,1), and (2,0) from the 2D array.
NumPy
import numpy as np
arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
rows = [0, 1, 2]
cols = [2, 1, 0]
result = arr[rows, cols]
print(result)
Selects elements (0,1) and (2,0) from the array.
NumPy
arr = np.array([[1, 2], [3, 4], [5, 6]])
rows = np.array([0, 2])
cols = np.array([1, 0])
result = arr[rows, cols]
print(result)
Sample Program

This program creates a 3x3 array and picks elements at positions (0,2), (1,0), and (2,1) using multi-dimensional fancy indexing.

NumPy
import numpy as np

# Create a 3x3 array
arr = np.array([[5, 10, 15],
                [20, 25, 30],
                [35, 40, 45]])

# Define row and column indices to pick elements
row_indices = [0, 1, 2]
col_indices = [2, 0, 1]

# Use multi-dimensional fancy indexing
selected_elements = arr[row_indices, col_indices]

print("Original array:")
print(arr)
print("\nSelected elements:")
print(selected_elements)
OutputSuccess
Important Notes

The index arrays must have the same shape to select elements element-wise.

If you want all combinations of rows and columns, use np.ix_() instead.

Summary

Multi-dimensional fancy indexing lets you pick specific elements from arrays using lists of row and column positions.

It is useful for selecting scattered data points in any order.

Make sure the index arrays have the same shape for element-wise selection.