Skip to content

01-05: Exercises — NumPy Statistics

Notes reference: 01-05: NumPy Statistics and Analysis


Q1: Descriptive statistics

Compute mean, median, std, var, min, max, and range of a dataset.

Solution

import numpy as np

data = np.array([58, 72, 65, 88, 91, 47, 76, 83, 60, 74])

print(f"Mean:   {np.mean(data):.2f}")
print(f"Median: {np.median(data):.2f}")
print(f"Std:    {np.std(data):.2f}")
print(f"Var:    {np.var(data):.2f}")
print(f"Min:    {np.min(data)}")
print(f"Max:    {np.max(data)}")
print(f"Range:  {np.ptp(data)}")    # peak-to-peak = max - min


Q2: argmin and argmax

Find which student scored highest and lowest in a class.

Solution

import numpy as np

names  = ["Rahim", "Sara", "James", "Nadia", "Michael"]
scores = np.array([78, 92, 65, 88, 71])

print(f"Highest: {names[np.argmax(scores)]} ({np.max(scores)})")
print(f"Lowest:  {names[np.argmin(scores)]} ({np.min(scores)})")


Q3: Percentiles and quartiles

Compute Q1, Q2 (median), Q3, and the 90th percentile for a dataset.

Solution

import numpy as np

data = np.array([45, 55, 60, 65, 70, 72, 78, 82, 88, 91, 95])

q1, q2, q3 = np.percentile(data, [25, 50, 75])
p90        = np.percentile(data, 90)

print(f"Q1:  {q1}")
print(f"Q2:  {q2}")
print(f"Q3:  {q3}")
print(f"IQR: {q3 - q1}")
print(f"90th percentile: {p90}")


Q4: Population vs. sample standard deviation

Compute both population std (ddof=0) and sample std (ddof=1).

Solution

import numpy as np

data = np.array([4.0, 7.0, 13.0, 2.0, 9.0, 4.0, 6.0])

pop_std  = np.std(data, ddof=0)    # divide by N
samp_std = np.std(data, ddof=1)    # divide by N-1

print(f"Population std: {pop_std:.4f}")
print(f"Sample std:     {samp_std:.4f}")


Q5: Cumulative sum and diff

Given monthly sales data, compute cumulative totals and month-over-month changes.

Solution

import numpy as np

monthly_sales = np.array([12000, 15000, 13500, 18000, 21000, 19500])

cumulative = np.cumsum(monthly_sales)
changes    = np.diff(monthly_sales)

print("Monthly:   ", monthly_sales)
print("Cumulative:", cumulative)
print("MoM change:", changes)


Q6: Axis-wise statistics on 2D

Given a 4×3 matrix of student scores (rows = students, cols = subjects), compute: - Max score per student - Average score per subject

Solution

import numpy as np

scores = np.array([
    [80, 75, 90],
    [88, 92, 85],
    [70, 65, 78],
    [95, 88, 91],
])

print("Max per student:", np.max(scores, axis=1))   # [90 92 78 95]
print("Avg per subject:", np.mean(scores, axis=0))  # [83.25 80.   86.  ]


Q7: Normalize an array

Normalize a score array to the range [0, 1] using min-max normalization.

Solution

import numpy as np

scores = np.array([45, 60, 78, 92, 55, 88, 70])

normalized = (scores - scores.min()) / (scores.max() - scores.min())
print(np.round(normalized, 3))
# [0.    0.319 0.702 1.    0.213 0.915 0.532]


Q8: Random distributions

Generate 1000 samples from a normal distribution (mean=170, std=02 for heights in cm) and compute summary stats.

Solution

import numpy as np

np.random.seed(0)
heights = np.random.normal(loc=170, scale=02, size=1000)

print(f"Mean:   {np.mean(heights):.2f} cm")
print(f"Std:    {np.std(heights):.2f} cm")
print(f"Min:    {np.min(heights):.2f} cm")
print(f"Max:    {np.max(heights):.2f} cm")
print(f"Median: {np.median(heights):.2f} cm")

# What fraction are above 180 cm?
above_180 = np.mean(heights > 180)
print(f"Above 180 cm: {above_180*100:.1f}%")


⬅️ Previous: 01-04: Exercises — NumPy 2D Arrays ➡️ Next: 02-01: Exercises — Matplotlib Basics