Written and maintained by CASRAI Editorial Board
Published
On this page
numpy.mean (np.mean) returns the arithmetic mean of an array, either over every element or along an axis you choose. This guide is for researchers and analysts who need to compute means in Python and know what happens with missing values, weights and floating-point precision. Syntax and defaults below follow the NumPy reference documentation (read 2026-11-08); the code examples were also run against NumPy 2.5.1.
What np.mean is used for in research
In research code the mean is the usual first summary of a measurement column: a mean response time per participant, a mean assay reading per plate, a mean pixel intensity per image. np.mean does this on NumPy arrays without a loop. Related questions are answered in their own sections: how numpy.average differs (weights), how nanmean handles missing data, and why a plain np.mean returns nan. For other summaries see the median in NumPy, np.sum and np.min.
Install or access
NumPy is open-source software distributed through the official NumPy project (numpy.org). Install it with the Python package manager and import it by the conventional alias:
pip install numpyimport numpy as np
The function is documented at numpy.org/doc/stable/reference/generated/numpy.mean.html.
Step by step: computing a mean
The signature in the current documentation is:
numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>)
- Create or load an array.
a = np.array([[1, 2], [3, 4]]) - Call it with no axis to average every element. By default the mean is taken over the flattened array:
np.mean(a)returns2.5. - Choose an axis to average down columns or across rows.
axismay be an int or a tuple of ints.np.mean(a, axis=0)returnsarray([2., 3.])(column means) andnp.mean(a, axis=1)returnsarray([1.5, 3.5])(row means). - Keep the dimensions if you need to broadcast the result back.
keepdims=Trueleaves the reduced axes in the result with size one:np.mean(a, keepdims=True)givesarray([[2.5]]). - Average only some elements with
where=. Thewhereargument is new in NumPy 1.20.0. Forb = np.array([5, 9, 13]),np.mean(b, where=[True, False, True])returns9.0. - Set
dtypewhen precision matters. For integer input the default accumulator dtype is float64; for floating-point input it is the input dtype. Usenp.mean(x, dtype=np.float64)for float32 data (see troubleshooting).
The documentation also shows np.mean working on timedelta64 arrays: np.mean(np.array([1, 3], dtype="timedelta64[D]")) returns np.timedelta64(2,'D').
Output and how to read it
With axis=None you get a single scalar; with an axis you get an array one dimension smaller (unless keepdims=True). The mean of integers is a float, so 2.5, not 2.
numpy average: weighted means
Use np.average when observations should count unequally; use np.mean when they should count equally. The documented signature is numpy.average(a, axis=None, weights=None, returned=False, *, keepdims=<no value>), and with weights the result is sum(a*weights)/sum(weights). Without weights it equals the plain mean. keepdims on average is new in NumPy 1.23.0, and returned=True additionally returns the sum of the weights.
Worked example: three groups report mean scores of 4.2, 5.1 and 3.9 from 10, 40 and 25 participants. The unweighted mean ignores group size; the weighted mean does not (outputs checked on NumPy 2.5.1):
m = np.array([4.2, 5.1, 3.9])n = np.array([10, 40, 25])np.mean(m) # 4.4np.average(m, weights=n) # 4.58np.average(m, weights=n, returned=True) # (4.58, 75.0)
The pooled mean of 4.58 is the correct overall mean of all 75 participants; the unweighted 4.4 is only the mean of the three group means.
mean numpy with missing values: nanmean
A plain np.mean propagates NaN: one missing value makes the result nan. np.nanmean computes the sum of the non-NaN elements divided by the number of non-NaN elements. Its where argument is new in NumPy 1.22.0.
v = np.array([4.1, 3.8, np.nan, 5.0, 4.4])np.mean(v) # nannp.nanmean(v) # 4.325x = np.array([[120., 135., np.nan], [98., np.nan, 110.]])np.nanmean(x, axis=1) # array([127.5, 104. ])
Skipping missing values is an analysis decision, not just a coding one: it assumes the values are missing for reasons unrelated to what you are measuring. See the standard error of the mean for how the number of non-missing observations enters the uncertainty of the mean.
Which function should I use?
| Situation | Function | Behaviour (per NumPy documentation) |
|---|---|---|
| Equal-weight mean, no missing data | np.mean |
Averages all elements or along axis |
| Observations count unequally | np.average(a, weights=w) |
sum(a*w)/sum(w); sum(w) must not be 0 |
| Array contains NaN to be skipped | np.nanmean |
Sum of non-NaN elements divided by their count |
| Only a masked subset should count | np.mean(a, where=mask) |
Requires NumPy 1.20.0 or later |
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
np.mean returns nan |
NaN in the input propagates | Use np.nanmean after deciding that skipping missing values is appropriate |
| Mean of a float32 array is slightly off | The mean is computed at the input precision, which can be inaccurate for float32 | Pass dtype=np.float64. The documentation’s example gives 0.54999924 in float32 and about 0.55000000074505806 with float64 (the exact digits may vary) |
TypeError from np.average |
With axis=None, weights must have the same shape as a; mismatched shapes raise “Axis must be specified when shapes of a and weights differ.” |
Match shapes, or give axis and a 1-D weight vector of the right length |
ValueError from np.average |
Weights are inconsistent with the array along the chosen axis | Make the weight length equal the length of a along that axis |
ZeroDivisionError from np.average |
The weights sum to zero | Check the weights; the documentation points to numpy.ma.average for that case |
RuntimeWarning from np.nanmean |
A slice is all NaN, so the result is NaN | Check for entirely missing rows or columns before averaging |
Floating-point rounding is a property of the number format; see IEEE 754 for background.
Free alternatives
| Tool | Equivalent | Note |
|---|---|---|
| Python standard library | statistics.mean |
For plain lists, without NumPy arrays |
| pandas | Series.mean() / DataFrame.mean() |
Skips missing values by default |
| R | mean(x, na.rm = TRUE) |
Base R, for users working outside Python |
These are the common equivalents in free software; check each project’s own documentation for argument details before relying on them in a pipeline.
FAQ
What does np.mean do by default?
It averages all elements of the flattened array and returns a scalar. Integer input is accumulated in float64.
What is the difference between numpy mean and numpy average?
np.average accepts a weights argument; np.mean does not. With no weights they give the same value.
How do I ignore NaN when taking a mean in NumPy?
Use np.nanmean, which divides the sum of non-NaN elements by their count.
Can I take the mean over more than one axis?
Yes. axis may be a tuple of ints.
Sources
- NumPy reference: numpy.mean (read 2026-11-08)
- NumPy reference: numpy.average (read 2026-11-08)
- NumPy reference: numpy.nanmean (read 2026-11-08)







