NumPy unravel index converts flat positions into coordinates for a chosen shape
A single position number can identify an entry in a flattened array, while a multidimensional array needs one coordinate per axis. NumPy unravel index connects those descriptions. Academia Master Trader presents this English lesson for readers in Senegal, using a constructed grid to explain shape, traversal order and the structure of returned coordinates.
Start with a shape and a flat position
After import numpy as np, define grid = np.arange(12).reshape(3,4). The grid has three rows and four columns. Its rows contain [0,1,2,3], [4,5,6,7] and [8,9,10,11].
The call np.unravel_index(9,grid.shape) returns (2,1). These are zero-based coordinates: row two and column one. The expression grid[2,1] returns nine.
In this deliberately numbered grid, the value happens to equal its flat position. The function does not inspect stored values or search for a matching entry. It calculates coordinates from the supplied position and shape.

C order moves through the final axis first
The default order is order='C'. In a two-dimensional grid, this means moving across a row before advancing to the next row.
For shape (3,4), flat position nine covers two complete rows of four entries, followed by one additional column position. The resulting coordinates are therefore (2,1).
Changing the supplied shape changes the interpretation. The call np.unravel_index(9,(4,3)) returns (3,0): three complete rows of three entries, with no additional column movement.
Both shapes contain twelve positions. Equal total size does not make their coordinates interchangeable. Keep the shape beside the flat position whenever coordinates will be used later.
F order follows a different traversal
The call np.unravel_index(9,(3,4),order='F') returns (0,3). Column-major traversal advances along the first axis before moving to the next column.
This argument describes how the flat index is interpreted. It does not rotate a grid, transpose values or change an existing array's shape.
An index produced under one traversal order must be interpreted under that same order. A valid coordinate pair can still point to the wrong intended entry if the flattening convention is mismatched.
Several positions return one array per axis
The call np.unravel_index([0,5,11],(3,4)) returns row coordinates [0,1,2] and column coordinates [0,1,3].
The returned tuple is organized by axis, not by entry. Pair corresponding positions to obtain (0,0), (1,1) and (2,3). Each coordinate array retains the shape of the supplied index array.
For this twelve-position grid, valid flat indices run from zero through eleven. A flat index of twelve is outside the supplied shape, rather than the first position of a new row.
Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Record the shape, zero-based index and traversal order before interpreting a flat position as coordinates.