Lesson 15
Statistics
Summarize arrays with max, min, argmax, mean, median, variance, and standard deviation, for the whole array or per row and column.
Statistics functions reduce many values to one. Called on the whole array, they give one number. With axis=0 they give one result per column, and with axis=1 one result per row.
max, min, and their positions
np.max and np.min find the extremes. You may also see them as np.amax and np.amin, which are older names for the same thing. np.argmax and np.argmin give the position instead of the value.
import numpy as np
A = np.array([[1, 2, 3], [4, 2, 1], [3, 4, 2]])
print(np.max(A), np.min(A))
print(np.max(A, axis=0))
print(np.max(A, axis=1))
print(np.min(A, axis=0))
print(np.argmax(np.array([7, 19, 4, 19])))Output:
4 1
[4 4 3]
[3 4 4]
[1 2 1]
1mean and median
The mean is the sum divided by the count. The median is the middle value after sorting. With an even count, it is the average of the two middle values. One very large value moves the mean a lot and the median very little.
import numpy as np
A = np.array([[1, 2, 3], [4, 2, 1], [3, 4, 2]])
print(round(np.mean(A), 3))
print(np.round(np.mean(A, axis=0), 3))
print(np.median(A), np.median(A, axis=1))
print(np.median(np.array([2, 3, 4, 1])))
salaries = np.array([30, 32, 35, 38, 400])
print(np.mean(salaries), np.median(salaries))Output:
2.444
[2.667 2.667 2. ]
2.0 [2. 2. 3.]
2.5
107.0 35.0variance and standard deviation
Variance is the mean of the squared distances from the mean. The standard deviation is its square root, back in the original units. The last line checks the formula by hand.
import numpy as np
A = np.array([[1, 2, 3], [4, 2, 1], [3, 4, 2]])
print(round(np.var(A), 4))
print(round(np.std(A), 4))
print(np.round(np.std(A, axis=0), 4))
by_hand = ((A - A.mean()) ** 2).mean()
print(round(by_hand, 4), round(np.sqrt(by_hand), 4))Output:
1.1358
1.0657
[1.2472 0.9428 0.8165]
1.1358 1.0657mode
NumPy has no mode function. The statistics module in the standard library has mode, which gives the first most common value, and multimode, which gives every value tied for most common.
import statistics
import numpy as np
visits = np.array([20, 10, 30, 10, 20, 40, 10, 20])
print(statistics.mode(visits.tolist()))
print(statistics.multimode(visits.tolist()))Output:
20
[20, 10]Key takeaways
-
No axis gives one number.
axis=0gives one per column,axis=1one per row -
argmaxandargmingive positions -
The median resists outliers better than the mean
-
stdis the square root ofvar.modelives instatistics -
Previous: Arithmetic and Broadcasting
Loading playground…
Check your understanding
Statistics Quiz
What is np.max(A) for A = [[1, 2, 3], [4, 2, 1], [3, 4, 2]]?
1 / 10