pythonintermediate

NumPy Advanced Indexing Patterns

Use fancy indexing, boolean masks, and np.where for fast array transformations without loops.

python
import numpy as np

rng = np.random.default_rng(42)
arr = rng.integers(0, 100, size=(5, 5))

mask = arr > 50
print('Values > 50:', arr[mask])
print(arr[[0, 2, 4]])
result = np.where(arr > 50, arr, 0)
print(result)
clipped = np.clip(arr, 20, 80)
print(clipped.mean())

Use Cases

  • numerical computing
  • array transformations
  • feature engineering

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.