Introduction
NumPy offers flexible and powerful indexing capabilities for accessing array elements.
Basic Indexing
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # First element: 10
print(arr[-1]) # Last element: 50
print(arr[1:4]) # Elements 1 to 3: [20, 30, 40]
2D Array Indexing
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Row access
print(matrix[0]) # First row
print(matrix[0, :]) # First row
# Column access
print(matrix[:, 1]) # Second column
# Element access
print(matrix[1, 2]) # Row 1, Col 2: 6
Fancy Indexing
arr = np.array([10, 20, 30, 40, 50])
# Index with list
print(arr[[0, 2, 4]]) # [10, 30, 50]
# Boolean indexing
mask = arr > 25
print(arr[mask]) # [30, 40, 50]
Practice Problems
- Extract diagonal from matrix
- Get even rows from 2D array
- Use boolean mask to filter values
- Replace negative values with zero
- Select random subset of array elements