CodeMIRAI
0 XP

Statistics

2 min read 4 runnable examples Quiz included

Summary statistics

Python
import numpy as np

sales = np.array([120, 135, 160, 150, 190, 220, 175])

print("total:  ", sales.sum())
print("mean:   ", sales.mean().round(2))
print("median: ", np.median(sales))
print("std dev:", sales.std().round(2))
print("min/max:", sales.min(), sales.max())
print("range:  ", np.ptp(sales))
print("index of max:", sales.argmax())

argmax() gives the position of the largest value, which is handy for finding the best day, the top scorer, and so on.

Percentiles

Python
import numpy as np

response_ms = np.array([120, 98, 230, 150, 101, 870, 140, 133, 99, 160])
print("median:", np.percentile(response_ms, 50))
print("90th:  ", np.percentile(response_ms, 90))
print("95th:  ", np.percentile(response_ms, 95))

Percentiles describe data with outliers better than the mean does: one slow 870 ms request drags the mean up, but barely moves the median.

Along rows or columns: axis

For 2D data, axis chooses the direction:

  • axis=0 works down the columns (one result per column),
  • axis=1 works across the rows (one result per row).
Python
import numpy as np

# rows = students, columns = maths, science, english
marks = np.array([[78, 85, 92],
                  [64, 70, 88],
                  [90, 95, 81]])

print("average per subject:", marks.mean(axis=0).round(1))
print("average per student:", marks.mean(axis=1).round(1))
print("best mark per subject:", marks.max(axis=0))
print("overall average:", marks.mean().round(1))

Cumulative totals

Python
import numpy as np

daily_steps = np.array([4200, 8100, 6500, 10300, 7600])
print(np.cumsum(daily_steps))     # running total
print(np.diff(daily_steps))       # change from the day before
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.