0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use Mean in NumPy: Simple Guide with Examples

Use numpy.mean() to calculate the average (mean) of array elements. You can apply it to the whole array or specify an axis to get the mean along rows or columns.
๐Ÿ“

Syntax

The basic syntax of numpy.mean() is:

  • numpy.mean(a, axis=None, dtype=None, out=None, keepdims=False)

Where:

  • a: Input array to find the mean of.
  • axis: Axis or axes along which to compute the mean. Default is None (mean of all elements).
  • dtype: Data type to use in computing the mean.
  • out: Alternative output array to place the result.
  • keepdims: If True, retains reduced dimensions with size 1.
python
numpy.mean(a, axis=None, dtype=None, out=None, keepdims=False)
๐Ÿ’ป

Example

This example shows how to calculate the mean of a 2D array overall and along specific axes.

python
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

mean_all = np.mean(arr)
mean_axis0 = np.mean(arr, axis=0)  # Mean of each column
mean_axis1 = np.mean(arr, axis=1)  # Mean of each row

print(f"Mean of all elements: {mean_all}")
print(f"Mean along axis 0 (columns): {mean_axis0}")
print(f"Mean along axis 1 (rows): {mean_axis1}")
Output
Mean of all elements: 3.5 Mean along axis 0 (columns): [2.5 3.5 4.5] Mean along axis 1 (rows): [2. 5. 4.]
โš ๏ธ

Common Pitfalls

Common mistakes when using numpy.mean() include:

  • Not specifying axis when you want the mean along rows or columns, which returns the mean of the entire array instead.
  • Using integer arrays without specifying dtype=float, which can cause integer division and incorrect results in older Python versions.
  • Confusing axis numbering: axis=0 means columns, axis=1 means rows in 2D arrays.
python
import numpy as np

arr = np.array([[1, 2], [3, 4]])

# Wrong: mean of entire array instead of rows
mean_wrong = np.mean(arr)

# Right: mean along rows
mean_right = np.mean(arr, axis=1)

print(f"Wrong mean (all elements): {mean_wrong}")
print(f"Right mean (rows): {mean_right}")
Output
Wrong mean (all elements): 2.5 Right mean (rows): [1.5 3.5]
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault
aInput arrayRequired
axisAxis to compute mean alongNone (all elements)
dtypeData type for computationNone (inferred)
outOutput array to store resultNone
keepdimsKeep reduced dimensionsFalse
โœ…

Key Takeaways

Use numpy.mean() to find the average of array elements easily.
Specify axis to get mean along rows (axis=1) or columns (axis=0).
Without axis, mean is calculated over the entire array.
Be careful with integer arrays to avoid unintended integer division.
Use keepdims=True to keep the original array dimensions after mean.