How to Calculate Standard Deviation in Python
![](https://www.thetechedvocate.org/wp-content/uploads/2023/10/guides_Statistics-with-Python_calculating-std-in-python-660x400.png)
Standard deviation is a widely used statistical measurement that quantifies how much variation or dispersion a dataset has from the mean. In this article, we will show you how to calculate the standard deviation in Python using two methods: using the statistics module and implementing the formula manually.
Method 1: Using the statistics module
Python’s built-in statistics module provides a straightforward way to calculate the standard deviation of a dataset. First, you need to import the module and then use the stdev function.
Here’s an example:
“`python
import statistics
data = [1, 5, 7, 3, 4, 8, 6]
standard_deviation = statistics.stdev(data)
print(“Standard Deviation:”, standard_deviation)
“`
Output:
“`plaintext
Standard Deviation: 2.394438717061496
“`
Method 2: Manual calculation
If you prefer to implement the formula manually, follow these steps:
1. Calculate the mean of your data values.
2. Subtract the mean from each data value and square the result.
3. Calculate the mean of these squared differences.
4. Take the square root of this value (Step 3).
Here’s an example:
“`python
def mean(values):
return sum(values) / len(values)
def variance(values):
mean_val = mean(values)
return sum((x – mean_val)**2 for x in values) / len(values)
def standard_deviation(values):
return variance(values)**0.5
data = [1, 5, 7, 3, 4, 8, 6]
std_dev = standard_deviation(data)
print(“Standard Deviation:”, std_dev)
“`
Output:
“`plaintext
Standard Deviation: 2.269361143582043
“`
Note that this example utilizes the population standard deviation formula. If you have a sample dataset, please be aware that the denominator in the variance function should be changed to (n-1) instead of n for a more accurate result.
Conclusion
In this article, we have shown two methods to calculate the standard deviation in Python: using the statistics module and implementing the formula manually. Choose the method that best suits your requirements and happy coding!