Statistical Functions in NumPy
Why statistics in NumPy?
Section titled “Why statistics in NumPy?”Quick descriptive stats help you:
- Understand distributions
- Detect outliers
- Summarize data before modeling/visualization
These aggregation methods (also called reductions) are available both as array methods (arr.mean()) and as top-level NumPy functions (np.mean(arr)) — they do the same thing.
Sample data
Section titled “Sample data”import numpy as np
data = np.array([12, 15, 14, 10, 25, 19, 18])Mean, median
Section titled “Mean, median”import numpy as np
data = np.array([12, 15, 14, 10, 25, 19, 18])
print(np.mean(data))
print(np.median(data))Min, max, range
Section titled “Min, max, range”import numpy as np
data = np.array([12, 15, 14, 10, 25, 19, 18])
print(np.min(data))
print(np.max(data))
print(np.ptp(data)) # peak-to-peak = max - minVariance and standard deviation
Section titled “Variance and standard deviation”import numpy as np
data = np.array([12, 15, 14, 10, 25, 19, 18])
print(np.var(data))
print(np.std(data))Percentiles / quantiles
Section titled “Percentiles / quantiles”import numpy as np
data = np.array([12, 15, 14, 10, 25, 19, 18])
print(np.percentile(data, 25))
print(np.percentile(data, 50))
print(np.percentile(data, 75))flowchart LR A["Raw array"] --> B["Center: mean, median"] A --> C["Spread: var, std, ptp"] A --> D["Position: percentile, quantile"] A --> E["Relationship (2 arrays):
cov, corrcoef"]
Working across axes (2D)
Section titled “Working across axes (2D)”import numpy as np
mat = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(np.mean(mat, axis=0)) # per column
print(np.mean(mat, axis=1)) # per rowCorrelation and covariance
Section titled “Correlation and covariance”import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])
cov = np.cov(x, y)
print("cov:\n", cov)
corr = np.corrcoef(x, y)
print("corr:\n", corr)Continue to: Saving and Loading NumPy Data to persist arrays efficiently.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Mean and Median
Section titled “Exercise 1 – Mean and Median”Exercise 2 – Standard Deviation
Section titled “Exercise 2 – Standard Deviation”Exercise 3 – Median via the 50th Percentile
Section titled “Exercise 3 – Median via the 50th Percentile”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading