Indexing & Slicing
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)
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
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
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.
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
Combine conditions with & (and), | (or) and ~ (not), and wrap each condition in brackets.
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)
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
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.
Tip: use the ← and → keys to move between pages.
