Summing and Axes

In two dimensions, the question is always which way you are collapsing.

Aggregating the whole array

sum, mean, min, max and std each reduce an array to one number when you do not say otherwise.

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.sum())
print(a.mean())

axis picks the direction

axis=0 collapses down the rows and leaves one value per column. axis=1 collapses across the columns and leaves one per row. Saying it out loud before you type it saves a lot of confusion.

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.sum(axis=0))
print(a.sum(axis=1))

Exercise

Try It Yourself

A table has one row per student and one column per test. Write student_totals(table) returning each student's total as a list.

Press Run to see output

Check Your Understanding