In this tutorial, you will learn how to access elements in a NumPy array using indexing techniques, including 1-D, 2-D, and 3-D arrays.
Indexing in 1-D Arrays
NumPy arrays use square bracket notation ([]) similar to Python lists for accessing elements.
Example:
import numpy as np
a = np.arange(0, 5)
print(a) # [0 1 2 3 4]
print(a[0]) # 0 (first element)
print(a[1]) # 1 (second element)
print(a[-1]) # 4 (last element)
print(a[-2]) # 3 (second last element)
-
Positive indices start from 0.
-
Negative indices start from -1 (last element) and go backward.
Indexing in 2-D Arrays
For 2-D arrays, you need two indices: one for the row (first axis) and another for the column (second axis).
Example:
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(a.shape) # (2, 3)
print(a[0]) # [1 2 3] - first row
print(a[1]) # [4 5 6] - second row
print(a[0, 0]) # 1
print(a[1, 0]) # 4
print(a[0, 2]) # 3
print(a[1, 2]) # 6
print(a[0, -1]) # 3 (last element in first row)
print(a[1, -1]) # 6 (last element in second row)
How it works:
-
a[0]returns the first row:[1 2 3] -
a[0, 2]selects the third element from the first row:3 -
a[1, -1]selects the last element from the second row:6
Indexing in 3-D Arrays
For 3-D arrays, use three indices: one for each axis.
Example:
import numpy as np
a = np.array([
[[1, 2], [3, 4], [5, 6]],
[[5, 6], [7, 8], [9, 10]]
])
print(a.shape) # (2, 3, 2)
print(a[0, 0, 1]) # 2
How it works:
-
a[0]returns:[[1, 2], [3, 4], [5, 6]] -
a[0, 0]returns:[1, 2] -
a[0, 0, 1]returns:2
Summary
-
Use square brackets
[]to index NumPy arrays. -
Positive indices count from the beginning (0-based).
-
Negative indices count from the end (-1 is the last element).
-
For multi-dimensional arrays, use a tuple of indices to access nested elements.
-
a[i, j]is used for 2-D arrays, anda[i, j, k]for 3-D arrays.
Copyright statement: Unless otherwise indicated, all articles are original to this site, please cite the source when sharing.
Article link:http://pybeginners.com/numpy/numpy-array-indexing/
License agreement:Creative Commons Attribution-NonCommercial 4.0 International License