Skip to main content
v2026.11,986 entries · CC-BY 4.0

NumPy Mean: np.mean Syntax, axis, dtype and NaN Handling

np.mean syntax, axis and dtype, when to use np.average or np.nanmean, and fixes for NaN results and weights errors.

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>)
  1. Create or load an array. a = np.array([[1, 2], [3, 4]])
  2. Call it with no axis to average every element. By default the mean is taken over the flattened array: np.mean(a) returns 2.5.
  3. Choose an axis to average down columns or across rows. axis may be an int or a tuple of ints. np.mean(a, axis=0) returns array([2., 3.]) (column means) and np.mean(a, axis=1) returns array([1.5, 3.5]) (row means).
  4. Keep the dimensions if you need to broadcast the result back. keepdims=True leaves the reduced axes in the result with size one: np.mean(a, keepdims=True) gives array([[2.5]]).
  5. Average only some elements with where=. The where argument is new in NumPy 1.20.0. For b = np.array([5, 9, 13]), np.mean(b, where=[True, False, True]) returns 9.0.
  6. Set dtype when precision matters. For integer input the default accumulator dtype is float64; for floating-point input it is the input dtype. Use np.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

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about NumPy Mean: np.mean Syntax, axis, dtype and NaN Handling

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →