NumPy Math · Examples
Data

NumPy Math Examples

Short, runnable programs that show numpy math and broadcasting in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the NumPy Math and Broadcasting lesson.

1Delivery distances with np.sqrt and np.abs

Maths functions apply to whole arrays of coordinates at once. Here the distance from the depot at (0, 0) to every stop comes from one expression, and np.abs measures how far each stop is east or west of a meeting point.

Delivery distances with np.sqrt and np.abs
import numpy as np

stops_x = np.array([3.0, -6.0, 5.0, 0.0])
stops_y = np.array([4.0, 8.0, -12.0, 5.0])

distance = np.sqrt(stops_x ** 2 + stops_y ** 2)
print("Distances:", distance)
print("Farthest stop:", distance.argmax(), "at", distance.max())
print("Offsets from x = 2:", np.abs(stops_x - 2))
print("Total route (rounded):", np.round(distance.sum(), 1))
Expected outputDistances: [ 5. 10. 13.  5.]
Farthest stop: 2 at 13.0
Offsets from x = 2: [1. 8. 3. 2.]
Total route (rounded): 33.0

2Running totals with cumsum and cumprod

cumsum keeps a running total and cumprod a running product. With the axis argument they work along rows or columns. Multiplying growth factors together shows how a balance changes month after month.

Running totals with cumsum and cumprod
import numpy as np

sales = np.array([[120, 135, 150, 90],
                  [80, 95, 70, 110],
                  [200, 180, 210, 190]])
print("Per region:", sales.sum(axis=1))
print("Best month overall (index):", sales.sum(axis=0).argmax())
print("Running total, region 0:", np.cumsum(sales[0]))
print("Running total across months, per region:")
print(sales.cumsum(axis=1))

growth = np.array([1.10, 1.05, 0.98, 1.20])
print("Balance factor:", np.round(np.cumprod(growth), 3))
Expected outputPer region: [495 355 780]
Best month overall (index): 2
Running total, region 0: [120 255 405 495]
Running total across months, per region:
[[120 255 405 495]
 [ 80 175 245 355]
 [200 380 590 780]]
Balance factor: [1.1   1.155 1.132 1.358]

3Broadcasting: rows, columns and tables

A row vector stretches down, a column vector stretches across. Multiplying a column by a row builds a whole multiplication table, and dividing by sum(axis=1, keepdims=True) turns each row into percentages.

Broadcasting: rows, columns and tables
import numpy as np

print(np.arange(1, 5)[:, None] * np.arange(1, 5))

votes = np.array([[30, 10, 60],
                  [5, 5, 10]])
shares = votes / votes.sum(axis=1, keepdims=True)
print(np.round(shares * 100, 1))

prices = np.array([[2.0, 3.0, 4.0],
                   [2.5, 3.5, 4.5]])
print(prices - prices.mean(axis=0))
Expected output[[ 1  2  3  4]
 [ 2  4  6  8]
 [ 3  6  9 12]
 [ 4  8 12 16]]
[[30. 10. 60.]
 [25. 25. 50.]]
[[-0.25 -0.25 -0.25]
 [ 0.25  0.25  0.25]]

4Reshape, transpose and ranges

Twelve monthly figures become 4 quarters of 3 months with reshape, and .T swaps rows and columns. linspace gives evenly spaced points including both ends, which is handy for chart axes, while arange counts in steps.

Reshape, transpose and ranges
import numpy as np

monthly = np.array([310, 280, 295, 340, 360, 390, 410, 405, 380, 350, 330, 420])
quarters = monthly.reshape(4, 3)
print(quarters)
print("Quarter totals:", quarters.sum(axis=1))
print("Month-of-quarter averages:", quarters.mean(axis=0))
print("Transposed shape:", quarters.T.shape)
print("Back to 1-D:", quarters.ravel().shape)
print("Chart axis:", np.linspace(0, 100, 5))
print("Every 5:", np.arange(0, 21, 5))
Expected output[[310 280 295]
 [340 360 390]
 [410 405 380]
 [350 330 420]]
Quarter totals: [ 885 1090 1195 1100]
Month-of-quarter averages: [352.5  343.75 371.25]
Transposed shape: (3, 4)
Back to 1-D: (12,)
Chart axis: [  0.  25.  50.  75. 100.]
Every 5: [ 0  5 10 15 20]

5Order totals with the matrix product

Each row of quantities is one order, each column is one item. quantities @ prices multiplies and adds across the items for every order in one step, and np.dot gives the same answer.

Order totals with the matrix product
import numpy as np

# columns: pens, notebooks, folders
quantities = np.array([[10, 2, 0],
                       [3, 0, 5],
                       [0, 4, 4]])
prices = np.array([1.20, 3.50, 2.00])

totals = quantities @ prices
print("Order totals:", totals)
print("Same with np.dot:", np.dot(quantities, prices))
print("Biggest order:", totals.argmax())
print("Revenue per item:", quantities.sum(axis=0) * prices)
Expected outputOrder totals: [19.  13.6 22. ]
Same with np.dot: [19.  13.6 22. ]
Biggest order: 2
Revenue per item: [15.6 21.  18. ]

6Cleaning sensor data: nan, clip and percentile

Sensors drop readings (nan) and sometimes report impossible spikes. Count the gaps with np.isnan, fill them with the average of the good readings, then use np.clip to limit the spikes and np.percentile to summarise.

Cleaning sensor data: nan, clip and percentile
import numpy as np

readings = np.array([20.5, np.nan, 21.0, 95.0, 19.5, np.nan, 22.0, -40.0])
print("Missing:", np.isnan(readings).sum())
print("Mean ignoring nan:", round(np.nanmean(readings), 2))

filled = np.where(np.isnan(readings), np.nanmedian(readings), readings)
print("Filled:", filled)
cleaned = np.clip(filled, 0, 40)
print("Clipped:", cleaned)
print("Median and 90th percentile:", np.median(cleaned), round(np.percentile(cleaned, 90), 2))
Expected outputMissing: 2
Mean ignoring nan: 23.0
Filled: [ 20.5   20.75  21.    95.    19.5   20.75  22.   -40.  ]
Clipped: [20.5  20.75 21.   40.   19.5  20.75 22.    0.  ]
Median and 90th percentile: 20.75 27.4

Practise next

NumPy Math and Broadcasting exercises → Back to the lesson

Python math and statistics examplesNumPy Basics examplesNumPy Indexing and Slicing examplesPandas Basics examples