← Data analysis with Python

The statistics module

Let Python’s built-in module do the arithmetic, and meet standard deviation.

Start this lesson

Python ships with a statistics module that already knows mean, median, mode and more, so you do not have to write them every time. It also has stdev, the standard deviation: roughly, how far values typically sit from the mean. A small standard deviation means values are bunched near the average; a large one means they are spread out. Unlike the range, it uses every value, so one odd reading does not dominate it as much.

import statistics as st

wait_minutes = [4, 6, 5, 7, 5, 30, 6]
print(st.mean(wait_minutes))
print(st.median(wait_minutes))
print(st.mode(wait_minutes))
print(round(st.stdev(wait_minutes), 2))

Writing import statistics as st lets you type st.mean(...). The 30-minute wait pulls the mean (9) above the median (6), and makes the standard deviation large.

st.multimode(values) returns a list of all the most common values when there is a tie.

You will meet stdev again in pandas: df["col"].std() gives the same number.