When working with multidimensional arrays, indexing allows you to select specific elements or slices of the array along each dimension.
In NumPy, indexing is done using integers or slices separated by commas inside square brackets. The number of integers or slices must match the number of dimensions in the array.
For example, consider a 2-dimensional NumPy array arr:
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) |
To select a single element from this array, we can use two integers separated by a comma inside square brackets:
>>> arr[1, 2]6 |
Here, we have selected the element in the second row and third column of the array.
To select a slice of the array along a particular dimension, we can use the : operator. For example, to select the first two rows of the array, we can use:
>>> arr[:2, :]array([[1, 2, 3], [4, 5, 6]]) |
Here, we have used : to select all columns of the first two rows.
We can also use boolean indexing to select elements based on a condition. For example, to select all elements in the array that are greater than 5, we can use:
>>> arr[arr > 5]array([6, 7, 8, 9]) |
This returns a 1-dimensional array containing all elements in the original array that satisfy the condition.
When working with arrays with more than two dimensions, we can use the same indexing syntax, with one integer or slice for each dimension. For example, consider a 3-dimensional array arr:
|
import numpy as np
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
|
To select a single element from this array, we can use three integers separated by commas inside square brackets:
>>> arr[1, 0, 1]6 |
Here, we have selected the element in the second row, first column, and second "depth" of the array.
We can also use slices and boolean indexing in the same way as for 2-dimensional arrays. For example, to select the first row of the second "depth" of the array, we can use:
>>> arr[1, :1, :]array([[5, 6]]) |