How does the axis parameter from NumPy work? How does the axis parameter from NumPy work? arrays arrays

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.


To understand the axis intuitively, refer the picture below (source: Physics Dept, Cornell Uni)

enter image description here

The shape of the (boolean) array in the above figure is shape=(8, 3). ndarray.shape will return a tuple where the entries correspond to the length of the particular dimension. In our example, 8 corresponds to length of axis 0 whereas 3 corresponds to length of axis 1.