Skip to content

NumPy

Indexing & Slicing

8 min+70 XPStep 1/10

Slicing reads like a sentence

NumPy indexing generalizes list indexing to every axis at once. For a = np.arange(6) → [0 1 2 3 4 5]:

  • a[0] → 0, and a[-1] → 5 — same as lists
  • a[1:4] → [1 2 3] — start included, stop excluded
  • a[::2] → [0 2 4] — a step of two

For a 2-D M, axes are comma-separated — M[row, col]:

  • M[0, :] → the first row
  • M[:, 2] → the third column — how you pull one feature out of a dataset
  • M[:2, :2] → the top-left block

df['col'] in pandas? This operation wearing a friendlier hat.