NumPy Statistics

Lesson 15 of 17

NumPy has built-in functions for the statistics you use every day: mean, median, standard deviation, percentiles, minimum and maximum.

Mean and median

Example

Python
import numpy as np

salaries = np.array([30, 32, 35, 38, 40, 120])  # in thousands

print(np.mean(salaries).round(2))
print(np.median(salaries))

Output

Plain Text
49.17
36.5

One very high salary pulls the mean up, while the median stays in the middle. That is why the median is often the better summary for skewed data.

Spread: standard deviation and variance

Example

Python
import numpy as np

salaries = np.array([30, 32, 35, 38, 40, 120])

print(np.std(salaries).round(2))
print(np.var(salaries).round(2))

Output

Plain Text
31.86
1014.81

Minimum, maximum and where they are

Example

Python
import numpy as np

temps = np.array([31, 28, 35, 26, 33])

print(temps.min(), temps.max())
print(temps.argmin(), temps.argmax())

Output

Plain Text
26 35
3 2

argmin() and argmax() return the position of the smallest and largest value.

Percentiles

Example

Python
import numpy as np

salaries = np.array([30, 32, 35, 38, 40, 120])
print(np.percentile(salaries, [25, 50, 75]))

Output

Plain Text
[32.75 36.5  39.5 ]

The 50th percentile is the median. The 25th and 75th percentiles mark the middle half of the data.

Statistics along an axis

With a 2-D array, choose whether to summarise each column or each row. Here rows are students and columns are subjects:

Example

Python
import numpy as np

marks = np.array([[80, 70, 90],
                  [60, 85, 75]])

print("Average per subject:", marks.mean(axis=0))
print("Average per student:", marks.mean(axis=1).round(1))

Output

Plain Text
Average per subject: [70.  77.5 82.5]
Average per student: [80.  73.3]

Missing values

A single np.nan (not a number) makes np.mean() return nan. The nan-prefixed functions skip missing values:

Example

Python
import numpy as np

readings = np.array([12.0, np.nan, 15.0, 18.0])

print(np.mean(readings))
print(np.nanmean(readings))

Output

Plain Text
nan
15.0