0
0
NumPydata~5 mins

np.unravel_index() for multi-dim positions in NumPy

Choose your learning style9 modes available
Introduction

We use np.unravel_index() to find the row and column positions in a multi-dimensional array from a single flat index. It helps us understand where a value is located in a grid or table.

You have a flat index from a flattened array and want to find its position in the original 2D or 3D array.
You want to convert a single number index into coordinates for image pixels in height and width.
You need to locate the position of the maximum or minimum value in a multi-dimensional dataset.
You want to map linear indices back to multi-dimensional indices for data analysis or visualization.
Syntax
NumPy
np.unravel_index(indices, shape, order='C')

indices can be a single integer or an array of integers representing flat indices.

shape is the shape of the multi-dimensional array you want to map to.

Examples
Find the 2D position of flat index 5 in a 3x3 array.
NumPy
np.unravel_index(5, (3, 3))
Find positions of flat indices 3 and 7 in a 3x3 array.
NumPy
np.unravel_index([3, 7], (3, 3))
Find the 3D position of flat index 10 in a 2x3x4 array.
NumPy
np.unravel_index(10, (2, 3, 4))
Sample Program

This code converts flat indices back to their row and column positions in a 3x4 array. It shows how to use np.unravel_index() for single and multiple indices.

NumPy
import numpy as np

# Suppose we have a 3x4 array
shape = (3, 4)

# Flat index to convert
flat_index = 7

# Get the multi-dimensional position
position = np.unravel_index(flat_index, shape)
print(f"Flat index {flat_index} corresponds to position {position} in shape {shape}.")

# For multiple indices
flat_indices = [5, 11]
positions = np.unravel_index(flat_indices, shape)
print(f"Flat indices {flat_indices} correspond to positions {positions} in shape {shape}.")
OutputSuccess
Important Notes

The output is a tuple of arrays, each array representing the indices along one dimension.

By default, order='C' means row-major order (like reading rows first).

You can use order='F' for column-major order if needed.

Summary

np.unravel_index() converts flat indices to multi-dimensional positions.

It works for any shape and can handle single or multiple indices.

This helps find exact locations in arrays from flat positions.