NumPy Array Indexing

Lesson 5 of 17

Array indexing means reading or changing a single element. Indexes start at 0, just like in Python lists.

Index a 1-D array

Example

Python
import numpy as np

arr = np.array([10, 20, 30, 40])

print(arr[0])
print(arr[2] + arr[3])

Output

Plain Text
10
70

Index a 2-D array

For a 2-D array, give the row index and the column index separated by a comma: arr[row, column].

Example

Python
import numpy as np

scores = np.array([[80, 92, 75],
                   [66, 88, 94]])

print("Row 0, column 1:", scores[0, 1])
print("Row 1, column 2:", scores[1, 2])

Output

Plain Text
Row 0, column 1: 92
Row 1, column 2: 94

Index a 3-D array

Example

Python
import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]],
                [[7, 8, 9], [10, 11, 12]]])

print(arr[1, 0, 2])

Output

Plain Text
9

arr[1, 0, 2] picks the second 2-D block, its first row, and the third value in that row: 9.

Negative indexing

Negative indexes count from the end: -1 is the last element.

Example

Python
import numpy as np

arr = np.array([[1, 2, 3, 4, 5],
                [6, 7, 8, 9, 10]])

print(arr[0, -1])
print(arr[-1, -2])

Output

Plain Text
5
9

Change a value

Example

Python
import numpy as np

arr = np.array([1, 2, 3])
arr[0] = 100
print(arr)

Output

Plain Text
[100   2   3]

Pick several elements at once

Pass a list of indexes to get several elements in one step. This is called fancy indexing.

Example

Python
import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(arr[[0, 2, 4]])

Output

Plain Text
[10 30 50]