Standard Deviation in Python – The Easiest Way

by:

PythonStatistics

How often do you need to calculate the Standard Deviation in Python for a list of elements? This short tutorial shows you how to do it in two different ways.

I’m sure you are not here to learn about the standard deviation formula. Thus, here we will focus on how to determine it using python by using the python module statistics and numpy.

1. Standard Deviation in Python using module statistics

Python has a native module named which can be easily imported and used to find it. Please see it below how to use it in a list of numbers:

# import statistics module
import statistics

# create list of numbers
list_numbers = [1, 2, 3, 4, 5, 6, 7]

# calculate std for numbers
std_numbers = statistics.stdev(list_numbers)

#print std
print(std_numbers)

# prints 2.160246899469287

You can also run it in a set of numbers

# import statistics module
import statistics

# create set of numbers
set_numbers = {1, 2, 3, 4, 5, 6, 7}

# calculate std for numbers
std_numbers = statistics.stdev(set_numbers)

# print std
print(std_numbers)

# prints 2.160246899469287

2. Numpy: Compute STD on Matrix columns or rows

In case you have numpy install in your machine, you can also compute the Standard Deviation in Python using numpy.std.

Numpy is great for cases where you want to compute it of matrix columns or rows.

# import numpy
import numpy

# create set of numbers
list_numbers = [[1.4, 5],[6,10]]

# calculate std for numbers
std_numbers_column = numpy.std(list_numbers, axis=0)

# print std for columns of matrix
print(std_numbers_column)

# prints [2.3 2.5]

# calculate std for numbers
std_numbers_row = numpy.std(list_numbers, axis=1)

# print std for row of matrix
print(std_numbers_row)

# prints [1.8 2. ]

More Resources

Here are three of my favorite Python Books in case you want to learn more about it.

Related Posts