Without an axis argument, mean() collapses the entire array into a single scalar average. Specifying axis=0 computes the mean down each column, collapsing rows, while axis=1 computes it across each row, collapsing columns — a common point of confusion, since the axis you specify is the one that gets reduced away, not the one that survives in the result.
1Understanding np.mean()
Without an axis argument, mean() collapses the entire array into a single scalar average. Specifying axis=0 computes the mean down each column, collapsing rows, while axis=1 computes it across each row, collapsing columns — a common point of confusion, since the axis you specify is the one that gets reduced away, not the one that survives in the result.
Remember the axis argument names the dimension being collapsed, not the one that remains — axis=0 on a 2D array reduces rows down to a single value per column, which trips people up expecting the opposite.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(np.mean(arr))2Practical Example
Here is a real-world application of np.mean() showing how it is used in production NumPy code.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(np.mean(matrix, axis=0))
print(np.mean(matrix, axis=1))3Best Practices
Follow these guidelines when working with np.mean():
1. Double-check whether axis=0 or axis=1 matches your intent by testing on a small example, since the reduced-vs-remaining dimension is easy to get backwards
2. Use np.nanmean() instead of np.mean() when the data might contain NaN values that should be ignored rather than propagating a NaN result
3. Prefer np.mean() over manually summing and dividing by the length, since it correctly handles multi-dimensional axes and NaN-aware variants
Tip: Remember the axis argument names the dimension being collapsed, not the one that remains — axis=0 on a 2D array reduces rows down to a single value per column, which trips people up expecting the opposite.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(np.mean(arr))