Lesson 13 of 60 · python
Advanced NumPy: Masking, Fancy Indexing, and Structured Arrays
Duration: 25 minutes
Advanced NumPy Techniques
When working with real data, you often need to filter, reshape, or work with heterogeneous structures.
Boolean masking (filtering)
arr = np.arange(20)
mask = (arr % 3 == 0) & (arr > 5)
filtered = arr[mask]
print(filtered) # [6 9 12 15 18]
Fancy indexing with integer arrays
rows = np.array([0, 2, 4])
cols = np.array([1, 3, 5])
mat = np.arange(30).reshape(5,6)
print(mat[rows, cols])
Structured arrays (heterogeneous data)
dtype = [('id', 'i4'), ('name', 'U10'), ('salary', 'f4')]
employees = np.array([(1, 'Alice', 70000), (2, 'Bob', 80000)], dtype=dtype)
print(employees['name'])
Sorting with argsort
scores = np.array([88, 92, 79, 93])
sorted_idx = np.argsort(scores)[::-1] # descending order
print(scores[sorted_idx])
Using np.where
x = np.arange(10)
y = np.where(x % 2 == 0, x**2, -x)
print(y)