TExcelTAD
Home › NumPy › NumPy Array Indexing

NumPy Array Indexing

Indexing means reading or writing one element of an array by its position. As with Python lists, positions start at 0.

python · try it yourself
import numpy as np

planets = np.array([0.39, 0.72, 1.00, 1.52, 5.20])   # distance from the Sun (AU)
print(planets[0])        # first
print(planets[3])        # fourth
print(planets[1] + planets[2])
0.39
1.52
1.72

Indexing 2-D arrays

A 2-D array has rows and columns. Give both positions separated by a comma: arr[row, col]. Think of it as "which row, then which column":

python · try it yourself
import numpy as np

# Seats sold per show: rows = days (Mon, Tue, Wed), columns = shows (2pm, 5pm, 8pm)
seats = np.array([[42, 77, 120],
                  [35, 80, 132],
                  [50, 91, 140]])

print("Tue 8pm:", seats[1, 2])
print("Mon 2pm:", seats[0, 0])
print("Whole Wed row:", seats[2])
Tue 8pm: 132
Mon 2pm: 42
Whole Wed row: [ 50  91 140]

seats[2] with a single index returns the whole row. You may also see seats[1][2], which works too, but it first builds the row and then indexes it; seats[1, 2] is the idiomatic and faster form.

Indexing 3-D arrays

Each extra dimension adds one more index. For a 3-D array the order is [layer, row, column]:

python · try it yourself
import numpy as np

# 2 warehouses x 2 shelves x 3 bins, values = item count
stock = np.array([[[5, 0, 2],
                   [7, 1, 3]],
                  [[9, 4, 0],
                   [6, 8, 2]]])

print(stock[1, 0, 1])    # warehouse 1, shelf 0, bin 1
print(stock[0, 1])       # warehouse 0, shelf 1 (all bins)
print(stock.shape)
4
[7 1 3]
(2, 2, 3)

Reading stock[1, 0, 1] step by step: stock[1] is the second 2×3 block, its row 0 is [9, 4, 0], and position 1 in that row is 4.

Negative indices

Negative numbers count from the end: -1 is the last element, -2 the one before, and so on. They work on every axis.

python · try it yourself
import numpy as np

grid = np.array([[1, 2, 3, 4],
                 [5, 6, 7, 8]])
print(grid[-1, -1])      # last row, last column
print(grid[0, -2])       # first row, second from the end
print(grid[-1])          # last row
8
3
[5 6 7 8]

Changing values

Indexing works on the left of = too. The new value is converted to the array's type, which can surprise you: assigning a float to an integer array truncates it.

python · try it yourself
import numpy as np

counts = np.array([3, 6, 9])
counts[0] = 100
counts[2] = 7.9           # stored as 7 because counts holds integers
print(counts)

matrix = np.zeros((2, 2))
matrix[1, 0] = 2.5
print(matrix)
[100   6   7]
[[0.  0. ]
 [2.5 0. ]]
Expression Meaning
a[i] element i of a 1-D array, or row i of a 2-D array
a[i, j] row i, column j
a[i, j, k] layer i, row j, column k
a[-1] last element / last row

Note: An index past the end raises IndexError, for example planets[5] on a 5-element array: "index 5 is out of bounds for axis 0 with size 5".

Test yourself

Given a = np.array([[1, 2], [3, 4], [5, 6]]), what is a[2, 0]?

  1. 2
  2. 3
  3. 5
  4. 6

What does a[-1] return for a 2-D array a?

  1. The last column
  2. The last row
  3. The last element of the first row
  4. An error

a = np.array([1, 2, 3]); a[0] = 9.7 — what is a now?

  1. [9.7 2 3]
  2. [9 2 3]
  3. [10 2 3]
  4. A TypeError