← Back to NumPy Course | Chapter 4: Indexing & Slicing | Lesson 5 of 7

Slicing 2D

Slice rows and columns at the same time to cut out a sub-table.

In this page:

  1. Slicing 2D
Syntax
python
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

python
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
  1. Forgetting the colon for a whole axis
  2. Mixing up row and column slices
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.