Chapter 4 · Part 2
Aggregations & axes
Often you don't want every number — you want a summary: the total, the average, the biggest.
NumPy has these built in, and one small argument, axis, controls whether you summarize the
whole array or just its rows or columns.
Reducing the whole array
Call these on any array to collapse it to a single number:
v = np.array([10, 20, 30, 40, 50])
v.sum() # 150
v.mean() # 30.0
v.min() # 10
v.max() # 50
v.std() # 14.142135... — standard deviationThe axis argument
On a 2-D array, axis picks the direction to collapse. Think of it as "which dimension
disappears": axis=0 collapses the rows (leaving one value per column), axis=1 collapses
the columns (one value per row):
grades = np.array([[80, 90, 70], # student 0
[60, 75, 95], # student 1
[100, 85, 90]]) # student 2
grades.sum() # 745 — everything
grades.mean(axis=1) # [80. 76.67 91.67] — each student's average (across subjects)
grades.max(axis=0) # [100 90 95] — top score in each subjectaxis=1 runs along each row, so it gives one number per student. axis=0 runs down each
column, giving one number per subject. Getting this right is most of the battle with NumPy.
Finding where, not just what
argmax and argmin return the index of the biggest or smallest value — handy for "who
won?" questions:
averages = grades.mean(axis=1) # [80. 76.67 91.67]
averages.argmax() # 2 — student 2 has the highest averageYou can summarize arrays in any direction. Next: changing their shape.