SciPy — Statistics
Descriptive statistics
from scipy import stats
import numpy as np
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(f"Mean: {stats.tmean(data):.2f}")
print(f"Variance: {stats.tvar(data):.2f}")
print(f"Skew: {stats.skew(data):.2f}")
print(f"Kurtosis: {stats.kurtosis(data):.2f}")
Distributions
from scipy import stats
# Normal distribution
normal = stats.norm(loc=0, scale=1)
print(f"PDF at 0: {normal.pdf(0):.4f}")
print(f"CDF at 1: {normal.cdf(1):.4f}")
# Generate random samples
samples = normal.rvs(size=1000)
Hypothesis testing
from scipy import stats
import numpy as np
# T-test
group1 = np.random.normal(0, 1, 100)
group2 = np.random.normal(0.5, 1, 100)
t_stat, p_value = stats.ttest_ind(group1, group2)
print(f"T-statistic: {t_stat:.4f}")
print(f"P-value: {p_value:.4f}")
Chi-square test
observed = [10, 20, 30, 40]
expected = [25, 25, 25, 25]
chi2, p_value = stats.chisquare(observed, expected)
print(f"Chi-square: {chi2:.4f}")
print(f"P-value: {p_value:.4f}")
Correlation
from scipy import stats
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
# Pearson correlation
r, p_value = stats.pearsonr(x, y)
print(f"Pearson r: {r:.4f}")
# Spearman correlation
rho, p_value = stats.spearmanr(x, y)
print(f"Spearman rho: {rho:.4f}")
Linear regression
from scipy import stats
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
print(f"Slope: {slope:.4f}")
print(f"Intercept: {intercept:.4f}")
Mini Practice
- Calculate descriptive statistics
- Fit a distribution to data
- Perform hypothesis testing
- Compute correlation
Up Next
Continue with Spatial Data - Spatial algorithms.
Related Topics
Frequently Asked Questions about Statistics
What is Statistics in SciPy?
Statistics is a fundamental concept in SciPy. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Statistics?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Statistics.
Why is Statistics important in SciPy?
Statistics is essential for SciPy development. Understanding this concept will help you write better code and solve real-world problems more effectively.