NumPy indices() Method | Create Array of Indices
The indices() method returns an array representing the indices of a grid.
It computes an array where the subarrays contain index values 0, 1, … varying only along the corresponding axis.
Example
Python3
import numpy as np gfg = np.indices(( 2 , 3 )) print (gfg) |
Output :
[[[0 0 0]
[1 1 1]]
[[0 1 2]
[0 1 2]]]
Syntax
numpy.indices(dimensions, dtype, sparse = False)
Parameters
- dimensions : [sequence of ints] The shape of the grid.
- dtype: [dtype, optional] Data type of the result.
- sparse: [boolean, optional] Return a sparse representation of the grid instead of a dense representation. Default is False.
Return: [ndarray or tuple of ndarrays] If sparse is False: Returns one array of grid indices, grid.shape = (len(dimensions), ) + tuple(dimensions). If sparse is True: Returns a tuple of arrays, with grid[i].shape = (1, …, 1, dimensions[i], 1, …, 1) with dimensions[i] in the ith place
How to Generate a Grid of Indices for a Given Shape in NumPy
To generate a grid of indices for a given shape we use numpy.indices() method of the NumPy library in Python.
Let us understand it better with an example:
Python3
import numpy as np grid = np.indices(( 2 , 3 )) gfg = grid[ 1 ] print (gfg) |
Output :
[[0 1 2]
[0 1 2]]