Course topics

By WebNest Studio Engineering Team

Python Tutorial

NumPy for Maths, Statistics and Linear Algebra

NumPy is also a complete numerical toolkit. This lesson covers the random number generator for simulations and sampling, descriptive statistics and correlation, sorting and searching, linear algebra (matrix multiplication, solving systems of equations, inverses), handling missing values with NaN, and saving and loading arrays — the maths you will meet again in machine learning.

Why it matters

Statistics, simulations and linear algebra are the mathematics behind data analysis and machine learning. NumPy provides them as tested, fast functions, so that solving a system of equations or computing a correlation is one call. Handling missing values correctly is part of the same toolkit and matters in every real dataset.

Random Numbers and Simulation

Create a generator with rng = np.random.default_rng(seed). Use integers, random (uniform 0–1), normal, choice (with replace and p for weights), shuffle and permutation. A fixed seed makes results reproducible — essential for experiments and machine learning. Simulations (Monte Carlo) estimate probabilities by generating many random trials at once with vectorised code.

Linear Algebra

A @ B (or np.dot) is matrix multiplication, while A * B multiplies element-wise. np.linalg provides solve (solve Ax = b), inv, det, norm, eig and lstsq (least squares, the maths behind linear regression). Prefer solve to multiplying by an inverse: it is faster and more accurate.

NaN, Sorting and Saving

Missing numeric values are represented by np.nan; any arithmetic with NaN gives NaN, so use np.nanmean, np.nansum and np.isnan. np.sort returns a sorted copy, argsort returns the order of indices (useful for ranking), and np.searchsorted finds insertion points. Save arrays with np.save/np.load (binary .npy) or np.savetxt/np.loadtxt for text.

Examples

Random sampling and a Monte Carlo simulation

Python
import numpy as np

rng = np.random.default_rng(seed=2026)
print(rng.choice(["heads", "tails"], size=6))
print(rng.choice(["red", "green", "blue"], size=5, p=[0.6, 0.3, 0.1]))
deck = np.arange(1, 11)
rng.shuffle(deck)
print(deck)

# Probability that two dice sum to 7 (exact answer: 1/6 = 0.1667)
rolls = rng.integers(1, 7, size=(1_000_000, 2))
print(round(np.mean(rolls.sum(axis=1) == 7), 3))

heights = rng.normal(loc=165, scale=8, size=10_000)
print(round(heights.mean(), 1), round(heights.std(), 1))
print("share taller than 180 cm:", round(np.mean(heights > 180), 3))
Output
['tails' 'heads' 'heads' 'tails' 'heads' 'heads']
['red' 'red' 'green' 'blue' 'red']
[ 6  9  4  1  5  8 10  2  7  3]
0.166
164.9 8.0
share taller than 180 cm: 0.03

Statistics, correlation, NaN handling and ranking

Python
import numpy as np

hours = np.array([1, 2, 3, 4, 5, 6, 7, 8])
marks = np.array([35, 45, 50, 58, 65, 72, 80, 88])
print("mean:", marks.mean(), "median:", np.median(marks), "var:", marks.var().round(1))
print("correlation:", np.corrcoef(hours, marks)[0, 1].round(3))
slope, intercept = np.polyfit(hours, marks, deg=1)       # best straight line
print(f"marks = {slope:.2f} * hours + {intercept:.2f}")

readings = np.array([21.5, np.nan, 23.0, 22.1, np.nan])
print(readings.mean(), np.nanmean(readings).round(2), np.isnan(readings).sum(), "missing")

scores = np.array([72, 95, 64, 88])
order = np.argsort(scores)[::-1]                          # indices, highest first
print(np.sort(scores), order, scores[order])
print(np.searchsorted([100, 200, 500, 1000], 350))        # which price band
Output
mean: 61.625 median: 61.5 var: 285.7
correlation: 0.999
marks = 7.37 * hours + 28.46
nan 22.2 2 missing
[64 72 88 95] [1 3 0 2] [95 88 72 64]
2

Matrix multiplication and solving equations

Python
import numpy as np

A = np.array([[2, 1],
              [1, 3]])
B = np.array([[1, 0],
              [4, 2]])
print(A * B)                   # element-wise
print(A @ B)                   # matrix product
print(np.linalg.det(A).round(2), np.linalg.inv(A).round(2).tolist())

# 3 pens + 2 notebooks = 160 ; 1 pen + 4 notebooks = 220 -> prices?
coefficients = np.array([[3, 2],
                         [1, 4]])
totals = np.array([160, 220])
pen, notebook = np.linalg.solve(coefficients, totals)
print(f"pen = {pen:.0f}, notebook = {notebook:.0f}")

np.save("prices.npy", np.array([pen, notebook]))
print(np.load("prices.npy"))
print(np.linalg.norm([3, 4]))  # length of a vector
Output
[[2 0]
 [4 6]]
[[ 6  2]
 [13  6]]
5.0 [[0.6, -0.2], [-0.2, 0.4]]
pen = 20, notebook = 50
[20. 50.]
5.0

Common Mistakes

  • Using * when you mean matrix multiplication (@).
  • Computing inv(A) @ b instead of np.linalg.solve(A, b).
  • Letting a single NaN turn every result into NaN — use nan-aware functions or clean the data.
  • Forgetting to set a seed, making experiments impossible to reproduce.
  • Comparing floats with == instead of np.isclose().

Exercise

Solve the pair of equations 2x + y = 5 and x + 3y = 10 with np.linalg.solve and print the solution rounded to 6 decimals as a list. Then print the matrix multiplied by the vector [1, 1], and the mean of a list that contains a missing value, ignoring that value.

Expected output: [1.0, 3.0], [3, 4], 2.0 (one per line)

Python · starter code
import numpy as np

coefficients = np.array([[2, 1],
                         [1, 3]])
constants = np.array([5, 10])

# TODO: solve for x and y, round to 6 decimals and print as a list

# TODO: print coefficients multiplied by the vector [1, 1], as a list

readings = np.array([1.0, np.nan, 3.0])
# TODO: print the mean of readings, ignoring the missing value
Show hints
  • np.linalg.solve(a, b) returns the solution, and np.round(result, 6) removes tiny floating-point errors.
  • Matrix multiplication uses the @ operator. np.nanmean skips nan values.
Show solution
Python · solution
import numpy as np

coefficients = np.array([[2, 1],
                         [1, 3]])
constants = np.array([5, 10])

solution = np.linalg.solve(coefficients, constants)
print(np.round(solution, 6).tolist())

print((coefficients @ np.array([1, 1])).tolist())

readings = np.array([1.0, np.nan, 3.0])
print(np.nanmean(readings))

Quick quiz

1. What does np.mean(np.array([1.0, np.nan, 3.0])) return?

  • A. nan
  • B. 2.0
  • C. 1.33
  • D. It raises an error
Show answer

A. Any calculation that includes nan gives nan. Use np.nanmean to ignore it.

2. For two-dimensional arrays, what does A @ B compute?

  • A. Element-by-element multiplication
  • B. The matrix product
  • C. The sum
  • D. The transpose
Show answer

B. A * B multiplies element by element.

3. Why create random numbers with np.random.default_rng(42)?

  • A. It is faster
  • B. It produces whole numbers only
  • C. The seed makes the results repeatable
  • D. It is required for arrays
Show answer

C. A fixed seed gives the same numbers on every run, which makes results reproducible.

Interview questions

What is NaN and how do you deal with it in NumPy?

Show answer

NaN, "not a number", is a special floating-point value used to mark missing or undefined data. It propagates through calculations, and it is not equal to anything, including itself, so it is detected with np.isnan() and not with ==. Functions such as np.nanmean and np.nansum ignore it, or the values can be removed or replaced using a boolean mask.

What is the difference between * and @ for arrays?

Show answer

* multiplies corresponding elements, so both arrays must have the same shape or be broadcastable. @ performs matrix multiplication: each row of the first is combined with each column of the second, and the number of columns of the first must equal the number of rows of the second. They give different results and are not interchangeable.

Key Points to Remember

  • default_rng(seed) gives reproducible random numbers for sampling and simulation.
  • mean, median, var, std, percentile, corrcoef and polyfit describe data.
  • @ multiplies matrices; np.linalg solves systems, inverts and decomposes them.
  • Handle NaN with isnan and nan-functions; sort with sort/argsort.
  • Save arrays with np.save/np.load.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

These examples need a project environment on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering