Skip to content
Kuza Ndoto Academy

Indexing & Slicing

Beginner → IntermediateChapter 2 · Page 6 of 204 min readUpdated 15 Nov 2026

Indexing and slicing let you pick out exactly the values you need from an array: one element, a range, a whole column, or every value that meets a condition. The same ideas carry straight over to pandas.

Indexing a 1-D array

Indexing works like it does for Python lists: positions start at 0, and negative positions count from the end.

import numpy as np

temps = np.array([22, 25, 27, 24, 30, 31, 26])   # daily highs in Nairobi, Mon to Sun

print(temps[0])     # first
print(temps[-1])    # last
print(temps[4])     # fifth (Friday)
22 26 30

Slicing

A slice uses start:stop:step. The stop position is not included, and any part can be left out.

print(temps[1:4])     # positions 1, 2, 3
print(temps[:3])      # first three
print(temps[4:])      # from position 4 to the end
print(temps[::2])     # every second value
print(temps[::-1])    # reversed
[25 27 24] [22 25 27] [30 31 26] [22 27 30 26] [26 31 30 24 27 25 22]

Indexing 2-D arrays

For a 2-D array, give the row and the column separated by a comma: array[row, column]. Each part can be a single position or a slice. Below, each row is a student and each column a subject.

scores = np.array([[65, 72, 80],    # Amina
                   [58, 90, 77],    # Brian
                   [88, 61, 70]])   # Chebet
# columns: Maths, English, Biology

print(scores[1, 2])     # Brian's Biology score
print(scores[0])        # Amina's whole row
print(scores[:, 1])     # every student's English score
print(scores[:2, 1:])   # first two students, English and Biology
77 [65 72 80] [72 90 61] [[72 80] [90 77]]

The colon on its own means "everything along this axis", so scores[:, 1] reads as "all rows, column 1". You can also write scores[1][2], but scores[1, 2] is clearer and faster.

Maths English Biology Amina Brian Chebet 65 72 80 58 90 77 88 61 70 scores[:2, 1:] rows 0–1, columns 1–2
Figure 1. scores[:2, 1:] keeps rows 0 and 1 (stopping before row 2) and columns 1 onwards, giving [[72 80] [90 77]].

Boolean indexing (filtering)

Put a Boolean array inside the square brackets and NumPy keeps only the positions where it is True. This is how you filter data by a condition.

print(temps[temps > 25])

warm_not_hot = temps[(temps > 23) & (temps < 30)]
print(warm_not_hot)

print(scores[scores[:, 0] >= 60])   # rows where the Maths score is at least 60
[27 30 31 26] [25 27 24 26] [[65 72 80] [88 61 70]]

Combine conditions with & (and), | (or) and ~ (not), and wrap each condition in brackets.

Common mistake

Writing temps > 23 and temps < 30 raises ValueError: The truth value of an array with more than one element is ambiguous. Python's and/or expect one True/False value, not a whole array. Use &/| with brackets: (temps > 23) & (temps < 30). The brackets matter because Python applies & before > and <; without them the comparison is evaluated in the wrong order and fails.

Fancy indexing and changing values

You can also pass a list of positions to pick several elements in any order, and assign new values to whatever you select.

print(temps[[0, 4, 5]])      # Monday, Friday and Saturday

capped = temps.copy()
capped[capped > 28] = 28     # cap every value above 28
print(capped)
[22 30 31] [22 25 27 24 28 28 26]

Views and copies

A basic slice does not copy the data. It is a view onto the same memory, so changing the slice changes the original array.

a = np.array([1, 2, 3, 4, 5])
b = a[1:4]        # a view
b[0] = 99
print(a)          # the original changed too

c = a[1:4].copy() # an independent copy
c[0] = 0
print(a)          # unchanged this time
[ 1 99 3 4 5] [ 1 99 3 4 5]
Note

Basic slices give views; Boolean and fancy indexing give copies. When you want to change a selection without touching the original, call .copy(). pandas has a similar (and famous) issue, covered on Cleaning Data.

Key points

  • Positions start at 0; negative positions count from the end; slices exclude the stop value.
  • Use array[row, column] for 2-D arrays, with : meaning "all".
  • Boolean indexing filters by condition; combine conditions with &, | and brackets.
  • Slices are views of the original; use .copy() for an independent array.
Up next · New chapter: pandasSeries & DataFramespandas' two core structures.
→

Tip: use the ← and → keys to move between pages.