How does the axis parameter from NumPy work?

Clearly,

e.shape == (3, 2, 2)

Sum over an axis is a reduction operation so the specified axis disappears. Hence,

e.sum(axis=0).shape == (2, 2)
e.sum(axis=1).shape == (3, 2)
e.sum(axis=2).shape == (3, 2)

Intuitively, we are “squashing” the array along the chosen axis, and summing the numbers that get squashed together.

Leave a Comment