Indexing picks single elements, slicing picks ranges, and boolean and fancy indexing pick elements by condition or position. These are the most used NumPy skills in data analysis.
Prerequisites
1D Indexing and Slicing
import numpy as np
a = np.arange(10, 20)
print(a)
print(a[0], a[-1])
print(a[2:5], a[:3], a[7:], a[::2], a[::-1])
Explanation: Same rules as Python lists: start:stop:step, stop excluded.
[10 11 12 13 14 15 16 17 18 19] 10 19 [12 13 14] [10 11 12] [17 18 19] [10 12 14 16 18] [19 18 17 16 15 14 13 12 11 10]
2D Indexing
m = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(m[1, 2]) # row 1, column 2
print(m[0]) # first row
print(m[:, 1]) # second column
print(m[0:2, 1:3]) # sub-matrix
Explanation: Use [row, column]. A colon alone means “all”.
6 [1 2 3] [2 5 8] [[2 3] [5 6]]
Boolean Indexing (Filtering)
marks = np.array([35, 82, 47, 91, 60])
print(marks > 50)
print(marks[marks > 50])
print(marks[(marks > 40) & (marks < 90)])
Explanation: A condition creates a True/False mask; using it as an index keeps only True positions. Combine conditions with & (and), | (or), ~ (not), with brackets around each.
[False True False True True] [82 91 60] [82 47 60]
Fancy Indexing
a = np.array([10, 20, 30, 40, 50])
print(a[[0, 2, 4]])
m = np.arange(9).reshape(3, 3)
print(m[[0, 2]])
[10 30 50] [[0 1 2] [6 7 8]]
Changing Values
marks = np.array([35, 82, 47, 91, 60])
marks[marks < 40] = 40
print(marks)
print(np.where(marks >= 50, 'Pass', 'Fail'))
[40 82 47 91 60] ['Fail' 'Pass' 'Fail' 'Pass' 'Pass']
Views vs Copies
a = np.arange(5)
s = a[1:4]
s[0] = 99
print(a)
c = a[1:4].copy()
[ 0 99 2 3 4]
.copy() when you need an independent array.Common Errors
| Problem | Cause and fix |
|---|---|
ValueError: The truth value of an array ... is ambiguous |
Use & and | instead of and/or, and put brackets around each condition. |
IndexError: index 3 is out of bounds |
Check the shape. |
Practice Exercises
- Get the last column of a 4×4 array.
- Replace all negative numbers in an array with 0.
- Get every other row of a 6×3 array.
Interview Questions
Q: Does slicing a NumPy array copy data?
No, it returns a view.
Q: How do you filter an array by condition?
Boolean indexing: a[a > 5].
Summary
Index with [row, col], slice with start:stop:step, filter with boolean masks, pick positions with lists, and remember slices are views.
Next: Sorting · Array Manipulation
Machine Learning Tutorials, Courses and Certifications