Slicing 2D
Slice rows and columns at the same time to cut out a sub-table.
In this page:
Syntax
arr[row_start:row_stop, col_start:col_stop]
arr[:, col]
arr[row, :]
Slicing 2D
Give one slice per axis separated by commas: arr[rows, cols]. A lone colon means everything on that axis. This makes it easy to extract rows, columns or rectangular blocks.
Note:
m[:, 1] selects the entire second column.
Example: Slicing 2D
import numpy as np
m = np.arange(1, 13).reshape(3, 4)
print(m)
print("column 1:", m[:, 1])
print("first two rows, last two cols:")
print(m[:2, 2:])
# Output:
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
# column 1: [ 2 6 10]
# first two rows, last two cols:
# [[3 4]
# [7 8]]
Related Topics
Common Mistakes
- Forgetting the colon for a whole axis
- Mixing up row and column slices
- Modifying a slice and forgetting it is a view
Chapter Summary
- Use arr[row_slice, col_slice]
- A colon means all
- m[:, j] is a column
- Results are views
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: