Summary numbers
import numpy as np a = np.array([12, 7, 25, 18, 3]) print(a.sum(), a.mean(), a.min(), a.max()) print(np.median(a)) print(round(a.std(), 3))
Write Python. Understand every error.
NumPy · topic 21 of 25
Aggregation functions summarise an array in a single value. Each one exists both as a method and as a function, so a.sum() and np.sum(a) are the same.
sum, mean, min, max, prodstd (standard deviation) and var (variance)np.median(a) and np.percentile(a, q)argmin and argmax give the position of the smallest and largest valueOn a 2D array, the axis argument chooses the direction. Think of axis as the dimension that disappears.
axis=0 works down each column, giving one result per columnaxis=1 works across each row, giving one result per rowmarks = np.array([[60, 70, 80], [50, 90, 75]]) print(marks.mean(axis=0)) # each subject: [55. 80. 77.5] print(marks.sum(axis=1)) # each student: [210 215]
For ordering data, np.sort(a) returns a sorted copy, np.argsort(a) gives the positions that would sort it, and np.unique(a) returns the distinct values in order. With return_counts=True it also counts them. np.cumsum(a) gives a running total.
sum, mean, min, max, std and var summarise an array, and np.median(a) gives the middle value.argmin and argmax give the position of the smallest and the largest value.axis=0 works down each column and axis=1 works across each row.axis, the result covers the whole array.axis=0 gives one result per column, not per row.argmax to return the largest value. It returns the position of that value.
import numpy as np a = np.array([12, 7, 25, 18, 3]) print(a.sum(), a.mean(), a.min(), a.max()) print(np.median(a)) print(round(a.std(), 3))
import numpy as np cities = np.array(["Kolkata", "Delhi", "Mumbai"]) rain_mm = np.array([1600, 800, 2200]) i = rain_mm.argmax() print(i, cities[i])
import numpy as np marks = np.array([[60, 70, 80], [50, 90, 75]]) print(marks.sum()) print(marks.mean(axis=0)) print(marks.sum(axis=1)) print(marks.max(axis=1))
import numpy as np a = np.array([3, 1, 3, 2, 1, 3]) print(np.sort(a)) print(np.argsort(np.array([30, 10, 20]))) values, counts = np.unique(a, return_counts=True) print(values) print(counts)
import numpy as np savings = np.array([500, 200, 300, 400]) print(np.cumsum(savings))
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
import numpy as np a = np.array([2, 4, 6, 8]) print(a.mean())
The mean is (2 + 4 + 6 + 8) / 4 = 5.0.
import numpy as np a = np.array([3, 9, 1, 7]) print(a.max(), a.argmax())
max is the largest value, and argmax is its position.
import numpy as np a = np.array([[1, 2], [3, 4]]) print(a.sum(axis=0))
axis=0 adds down each column: 1+3 and 2+4.
import numpy as np a = np.array([[1, 2], [3, 4]]) print(a.sum(axis=1))
axis=1 adds across each row: 1+2 and 3+4.
import numpy as np print(np.median(np.array([7, 1, 5])))
Sorted: 1, 5, 7. The middle value is 5.