NumPy Essentials

Arrays, vectorised operations, broadcasting and random numbers: the numerical engine underneath pandas.

Beginner · about 4 hours · difficulty 2/5

Learn first: Python for Analysts

NumPy provides fast arrays and vectorised maths. You will rarely build whole analyses in raw NumPy, but pandas is built on it, and understanding arrays makes pandas behaviour less mysterious.

Key ideas

  • ndarray: a fixed-type grid of numbers. np.array([1, 2, 3]), np.arange, np.linspace, np.zeros.
  • Vectorisation: prices * 1.1 applies to every element at C speed, far faster than a Python loop.
  • Broadcasting: operations between arrays of different shapes follow rules that let you, for example, subtract a column mean from every row.
  • Boolean masks: arr[arr > 100] selects elements, the same idea as pandas filtering.
  • Aggregations: mean, median, std, percentile, with axis to choose rows or columns.
  • Missing values: np.nan propagates through sums; use np.nanmean and friends.

Random numbers and simulation

rng = np.random.default_rng(42) then rng.normal, rng.binomial, rng.choice. Simulation is a great way to build statistical intuition and to bootstrap confidence intervals.

Pitfall: integer arrays silently truncating when you assign floats into them, and forgetting that axis=0 means "down the rows". Move on when you can bootstrap a confidence interval for a median in about 10 lines of NumPy.

Key concepts

  • Creating arrays
  • Vectorised operations
  • Broadcasting
  • Boolean masking
  • Aggregations and axis
  • NaN handling
  • Random generation and simulation

Mini project

Simulate 10,000 A/B tests with no true difference using NumPy's random generator and show that about 5% come out 'significant' at the 0.05 level.

Check yourself

Why is prices * 1.1 on a NumPy array much faster than a for loop doing the same thing?

Free resources