-->

Python - Python Machine Learning - Standard Deviation Part 2: Using Python Libraries for Standard Deviation

Python provides built-in functions to compute standard deviation quickly using NumPy and statistics modules.

Example 2: Using statistics Module

import statistics

data = [10, 20, 30, 40, 50]

std_dev = statistics.stdev(data)  # Sample standard deviation

pop_std_dev = statistics.pstdev(data)  # Population standard deviation

print("Sample Standard Deviation:", std_dev)

print("Population Standard Deviation:", pop_std_dev)

Output:

Sample Standard Deviation: 15.811388300841896

Population Standard Deviation: 14.142135623730951

Explanation:

statistics.stdev() calculates the sample standard deviation, which divides by (N-1).

statistics.pstdev() calculates the population standard deviation, which divides by N.

Example 3: Using NumPy

import numpy as np

data = [10, 20, 30, 40, 50]

std_dev = np.std(data)  # Population standard deviation

std_sample = np.std(data, ddof=1)  # Sample standard deviation

print("NumPy Population Standard Deviation:", std_dev)

print("NumPy Sample Standard Deviation:", std_sample)

Output:

NumPy Population Standard Deviation: 14.142135623730951

NumPy Sample Standard Deviation: 15.811388300841896

Explanation:

np.std(data) computes the population standard deviation.

np.std(data, ddof=1) adjusts the divisor for the sample standard deviation.