1D indexing and slicing
import numpy as np a = np.array([5, 10, 15, 20, 25, 30]) print(a[0], a[-1]) print(a[1:4]) print(a[::2]) print(a[::-1])
Write Python. Understand every error.
NumPy · topic 19 of 25
A 1D array is indexed just like a list: a[0] is the first element, a[-1] the last, and a[1:4] a slice.
A 2D array takes one index per dimension, separated by a comma: m[row, column]. Both start at 0.
m = np.array([[10, 20, 30], [40, 50, 60]]) print(m[1, 2]) # 60 print(m[0]) # first row: [10 20 30] print(m[:, 1]) # second column: [20 50]
A colon on its own means "everything along this dimension", so m[:, 1] reads as "all rows, column 1". Slices combine to cut out a block: m[0:2, 1:3] is rows 0 and 1, columns 1 and 2.
You can also pick several positions at once by passing a list of indexes, for example a[[0, 2, 5]]. This is called fancy indexing.
Indexing also works on the left of =, which changes values in place: m[0, 0] = 99 changes one element, and m[:, 1] = 0 sets a whole column.
One difference from real NumPy: in a full installation, a slice shares memory with the original array, so changing the slice changes the original too. This practice version always copies. Write .copy() whenever you want an independent copy, and your code will behave the same in both.
m[row, column].m[:, 1] is all rows of column 1.m[0:2, 1:3] is rows 0 and 1 and columns 1 and 2.= changes values in place.m[3, 0] in an array with three rows. Read the IndexError guide.m[0].
import numpy as np a = np.array([5, 10, 15, 20, 25, 30]) print(a[0], a[-1]) print(a[1:4]) print(a[::2]) print(a[::-1])
import numpy as np m = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) print(m[1, 2]) print(m[0]) print(m[:, 1]) print(m[-1, -1])
import numpy as np m = np.arange(1, 17).reshape(4, 4) print(m) print(m[1:3, 1:3])
import numpy as np a = np.array([11, 22, 33, 44, 55]) print(a[[0, 2, 4]]) m = np.arange(12).reshape(3, 4) print(m[[0, 2]])
import numpy as np m = np.zeros((3, 3), dtype=int) m[1, 1] = 5 m[:, 0] = 9 print(m)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
import numpy as np a = np.array([10, 20, 30, 40, 50]) print(a[1:4])
Slicing works like lists: indexes 1, 2 and 3.
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) print(a[1, 2])
a[row, column]: row 1, column 2 is 6.
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) print(a[:, 0])
: means all rows, and 0 picks the first column.
import numpy as np a = np.array([5, 6, 7]) print(a[-1])
Negative indexes count from the end.
import numpy as np a = np.arange(6).reshape(2, 3) print(a[0])
One index on a 2D array gives a whole row.