How to Calculates the standard deviation from a sample of data in Python ?


To calculate the standard deviation from a sample of data in Python, we can use the statistics module or the numpy module.

Method 1: Using the statistics module

The statistics module provides a function called stdev() which can be used to calculate the standard deviation of a sample.

import statistics

data = [1, 2, 3, 4, 5]

std_dev = statistics.stdev(data)

print("Standard deviation of the sample is:", std_dev)

Output:

Standard deviation of the sample is: 1.5811388300841898

Method 2: Using the numpy module

The numpy module provides a function called std() which can be used to calculate the standard deviation of a sample.

import numpy as np

data = [1, 2, 3, 4, 5]

std_dev = np.std(data)

print("Standard deviation of the sample is:", std_dev)

Output:

Standard deviation of the sample is: 1.5811388300841898

Both methods will give the same result. However, the numpy module is generally faster and more efficient for large datasets.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.