Python - NumPy

Overview

Estimated time: 30–45 minutes

NumPy provides fast n-dimensional arrays and vectorized operations for numerical computing.

Learning Objectives

  • Create arrays with correct dtypes and shapes.
  • Use broadcasting and vectorized operations.
  • Understand views vs copies and memory layout.

Examples

import numpy as np

x = np.array([1,2,3], dtype=np.float64)
y = np.array([10,20,30])
print(x + y)
print((x * 2).sum())

m = np.arange(12).reshape(3,4)
print(m[:, 1:3])

Guidance & Patterns

  • Prefer vectorization over Python loops for performance.
  • Use np.where, boolean masks, and broadcasting to express computations.

Best Practices

  • Be explicit about dtypes; avoid unintended up/down-casting.
  • Beware of views; modify copies when needed (.copy()).

Exercises

  1. Compute row-wise means for a large matrix using vectorized operations.
  2. Apply a mask to clamp values in an array to a range.