Indexing and slicing
One dimension
Python
import numpy as np
a = np.array([10, 20, 30, 40, 50, 60])
print(a[0], a[-1]) # first and last: 10 60
print(a[1:4]) # positions 1, 2, 3: [20 30 40]
print(a[:3]) # the first three
print(a[3:]) # from position 3 to the end
print(a[::2]) # every second element: [10 30 50]
print(a[::-1]) # reversedSlices work like Python's: start:stop:step, where stop is not included.
Two dimensions
Python
import numpy as np
m = np.array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
print(m[1, 2]) # row 1, column 2: 7
print(m[0]) # the whole first row
print(m[:, 1]) # the whole second column: [ 2 6 10]
print(m[0:2, 1:3]) # rows 0-1, columns 1-2: a 2 x 2 block
print(m[-1, -1]) # bottom-right: 12Use one pair of brackets with a comma, m[row, column]. Inside, : on its own means "everything along this axis".
Choosing several positions
Python
import numpy as np
scores = np.array([72, 95, 88, 61, 79])
print(scores[[0, 2, 4]]) # the elements at positions 0, 2 and 4
m = np.arange(1, 13).reshape(3, 4)
print(m[[0, 2]]) # rows 0 and 2
print(m[:, [3, 0]]) # columns 3 and 0, in that orderA list of indexes, often called fancy indexing, picks exactly those positions, in the order you give.
Where's the biggest?
Python
import numpy as np
temps = np.array([21.5, 24.0, 19.8, 26.3, 23.1])
days = np.array(["Mon", "Tue", "Wed", "Thu", "Fri"])
hottest = temps.argmax() # the POSITION of the maximum
print(hottest, days[hottest], temps[hottest])
print(days[temps.argmin()]) # the coolest day
print(days[np.argsort(temps)]) # days from coolest to hottestargmax and argmin return positions, not values, so you can use them to index a second, related array.
Slices are views
Python
import numpy as np
a = np.array([1, 2, 3, 4, 5])
part = a[1:4] # a view: it shares memory with a
part[0] = 99
print(a) # [ 1 99 3 4 5]: the original changed
b = np.array([1, 2, 3, 4, 5])
copy = b[1:4].copy() # an independent copy
copy[0] = 99
print(b) # unchangedA slice doesn't copy the data: it's a view onto the same memory. That makes slicing fast even on huge arrays, but changing the view changes the original. Call .copy() when you need an independent array. (Fancy indexing with a list always makes a copy.)
Changing values through an index
Python
import numpy as np
m = np.zeros((3, 4), dtype=int)
m[0] = 1 # a whole row
m[:, -1] = 9 # the last column
m[1:, 1:3] = 5 # a block
print(m)Finished this lesson?Mark it complete to earn +20 XP and move your progress on.