7/12
Advanced Indexing & Fancy Indexing · Page 1 of 1

Fancy Indexing Techniques

Advanced Indexing & Fancy Indexing

Beyond Basic Slicing

NumPy's fancy indexing allows you to select elements using arrays of indices, not just ranges.

Integer Array Indexing

arr = np.array([10, 20, 30, 40, 50])

# Select by index array
indices = np.array([0, 2, 4])
arr[indices]  # [10, 30, 50]

Boolean Indexing (Most Useful!)

arr = np.array([10, 20, 30, 40, 50])
mask = arr > 25  # [False, False, True, True, True]
arr[mask]        # [30, 40, 50]

2D Advanced Indexing

matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# Select rows [0, 2]
matrix[[0, 2]]        # rows 0 and 2

# Select by condition
matrix[matrix > 4]    # [5, 6, 7, 8, 9]

Key insight: Boolean indexing is the foundation of NumPy's speed advantage over lists for data analysis.

main.py
Loading...
OUTPUT
Click "Run Code" to execute…