Indexing

Index into NumPy arrays to extract data and array slices.

Chapter Goals:

  • Learn about indexing arrays in NumPy
  • Write code for indexing and slicing arrays

A. Array accessing

Accessing NumPy arrays is identical to accessing Python lists. For multi-dimensional arrays, it is equivalent to accessing Python lists of lists.

The code below shows example accesses of NumPy arrays.

Press + to interact
arr = np.array([1, 2, 3, 4, 5])
print(arr[0])
print(arr[4])
arr = np.array([[6, 3], [0, 2]])
# Subarray
print(repr(arr[0]))

B. Slicing

NumPy arrays also support slicing. Similar to Python, we use the colon operator (i.e. arr[:]) for slicing. We can also use negative indexing to slice in the backwards direction.

The code below shows example slices of a 1-D NumPy array.

Press + to interact
arr = np.array([1, 2, 3, 4, 5])
print(repr(arr[:]))
print(repr(arr[1:]))
print(repr(arr[2:4]))
print(repr(arr[:-1]))
print(repr(arr[-2:]))

For multi-dimensional arrays, we can use a comma to separate slices across each dimension.

The code below shows example slices of a 2-D NumPy array.

Press + to interact
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(repr(arr[:]))
print(repr(arr[1:]))
print(repr(arr[:, -1]))
print(repr(arr[:, 1:]))
print(repr(arr[0:1, 1:]))
print(repr(arr[0, 1:]))
...
Access this course and 1400+ top-rated courses and projects.