NumPy Array Slicing
Slicing selects a range of elements instead of one. The syntax is [start:stop:step], the same as for Python lists:
startis included (default0)stopis excluded (default: the end)stepis the stride (default1)
import numpy as np
hours = np.arange(24) # 0, 1, ..., 23
print(hours[9:17]) # office hours: 9 up to (not including) 17
print(hours[:6]) # night: start to 5
print(hours[20:]) # evening: 20 to the end
print(hours[::6]) # every 6th hour[ 9 10 11 12 13 14 15 16]
[0 1 2 3 4 5]
[20 21 22 23]
[ 0 6 12 18]
Negative values in slices
Negative start/stop count from the end, and a negative step walks backwards:
import numpy as np
letters = np.array(list("NUMPYROCKS"))
print(letters[-5:]) # last five
print(letters[-5:-2]) # from 5th-last up to (not incl.) 2nd-last
print(letters[::-1]) # reversed
print(letters[1::2]) # every second letter starting at index 1['R' 'O' 'C' 'K' 'S']
['R' 'O' 'C']
['S' 'K' 'C' 'O' 'R' 'Y' 'P' 'M' 'U' 'N']
['U' 'P' 'R' 'C' 'S']
Slicing 2-D arrays
Put one slice per dimension, separated by a comma: arr[rows, cols]. You can mix a slice on one axis with a plain index on another.
import numpy as np
# Monthly sales: 3 shops (rows) x 6 months (columns)
sales = np.array([[12, 15, 11, 18, 21, 19],
[ 8, 9, 14, 13, 10, 16],
[20, 22, 25, 24, 30, 28]])
print(sales[0, 1:4]) # shop 0, months 1-3
print(sales[:, 0]) # month 0 for every shop (a column)
print(sales[1:, -2:]) # shops 1-2, last two months
print(sales[:, ::2]) # every other month[15 11 18]
[12 8 20]
[[10 16]
[30 28]]
[[12 11 21]
[ 8 14 10]
[20 25 30]]
sales[:, 0] is the classic way to pull out a column: : means "all rows", and 0 picks the first column.
| Slice | Selects |
|---|---|
a[1:3] |
rows 1 and 2 |
a[:, 2] |
column 2 as a 1-D array |
a[:, 2:3] |
column 2 as a 2-D array (one column wide) |
a[::2, ::2] |
every other row and column |
a[-1, :] |
the last row |
Note the difference between a[:, 2] (shape (3,)) and a[:, 2:3] (shape (3, 1)): an integer index removes that dimension, a slice keeps it.
Assigning to a slice
A slice can be assigned in one go. A single value is copied to every selected position:
import numpy as np
board = np.zeros((5, 5), dtype=int)
board[0, :] = 1 # top edge
board[-1, :] = 1 # bottom edge
board[:, 0] = 1 # left edge
board[:, -1] = 1 # right edge
board[2, 1:4] = [7, 8, 9] # values for part of the middle row
print(board)[[1 1 1 1 1]
[1 0 0 0 1]
[1 7 8 9 1]
[1 0 0 0 1]
[1 1 1 1 1]]
Important: Unlike list slices, a NumPy slice is a view of the original data, not a copy. Changing the slice changes the original array. The Copy vs View lesson explains this in detail.
import numpy as np
data = np.array([1, 2, 3, 4, 5])
middle = data[1:4]
middle[:] = 0
print(data) # the original changed too![1 0 0 0 5]
Test yourself
What does np.arange(10)[2:8:3] return?
- [2 5]
- [2 5 8]
- [3 6]
- [2 3 4]
For a 2-D array a, how do you select the whole second column?
- a[1]
- a[:, 1]
- a[1, :]
- a[1:2]
After b = a[0:2]; b[0] = 99, what happens to a?
- Nothing, b is a copy
- a[0] becomes 99
- An error is raised
- a is resized