axis (NumPy)

An axis is a single dimension of a NumPy array; axis=0 runs down the rows and axis=1 runs across the columns in a 2-D array. The axis argument tells aggregations and operations which direction to act along.

NumPy

The clearest way to read axis is 'the axis that disappears.' a.sum(axis=0) collapses the rows, leaving one value per column; a.sum(axis=1) collapses the columns, leaving one value per row. Omitting axis aggregates over the whole array to a single scalar.

Axes are numbered from the outside in: axis 0 is the outermost (the first shape entry), and higher axes go deeper. For a 3-D array of shape (a, b, c), axis 0 has length a, axis 1 has length b, and axis 2 has length c. Negative axes count from the end, so axis=-1 is always the last.

Getting the axis right is the crux of most NumPy and pandas aggregation bugs — when a sum or mean comes out the wrong shape, the axis argument is usually the culprit.

Syntax

a.sum(axis=0)  |  a.mean(axis=1)

Examples

Python

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

Output:

[5 7 9]
[ 6 15]

Learn it in a lesson

See also

Back to the Dictionary