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

pandas mean: DataFrame.mean() Syntax, Examples and Errors

How pandas mean() works: arguments, skipna, axis, numeric_only, group means and common errors, with outputs run on pandas 3.1.1.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

In pandas, mean() returns the arithmetic average of the values in a Series or DataFrame. df['col'].mean() gives one number for a single column, df.mean() gives one mean per column, and df.mean(axis=1) gives one mean per row. By default missing values are skipped (skipna=True) and, in the current documentation, a column of text raises an error unless you pass numeric_only=True.

This guide uses the signature in the pandas 3.1.1 documentation, DataFrame.mean(*, axis=0, skipna=True, numeric_only=False, **kwargs), and a small worked table of laboratory-style measurements whose outputs were produced by running the code on pandas 3.1.1. The table is a labelled illustrative composite, not real study data.

What it is used for in research

The mean is the usual first summary of a continuous measurement: mass, concentration, reaction time, a survey score. In a research workflow, mean() appears in three places: quick checks while cleaning data (does the column average look plausible?), the central-tendency row of a descriptive-statistics table, and group comparisons built with groupby. The mean is one of several summaries; Series.median, Series.std, Series.var, Series.sum, Series.min and Series.max are listed as related methods on the official Series.mean page.

Editorial note: the mean is sensitive to extreme values. When a variable is skewed or contains outliers, report the median alongside it. That is general statistical practice rather than a statement from the pandas documentation. For the standard deviation and related spread measures see the pandas documentation for std; for pairwise relationships see pandas corr.

How to install or access it

The pandas installation page lists these official routes:

  • pip install pandas for a pip-based environment.
  • conda install -c conda-forge pandas to add pandas to an existing conda environment, or conda create -c conda-forge -n name_of_my_env python pandas followed by conda activate name_of_my_env to create a new one.
  • pip install "pandas[excel]" if you also need the optional Excel readers and writers.

The installation page does not give a minimum Python version; it points to the Python support policy for that. Then import the library with the conventional alias: import pandas as pd.

Step-by-step: computing a mean in pandas

The steps below use this small dataset (an illustrative composite): five samples, two groups, one column with a missing mass and one concentration column that was read in as text because a lab sheet contains n/a.

import pandas as pddf = pd.DataFrame({    "sample_id": ["S1", "S2", "S3", "S4", "S5"],    "group": ["control", "control", "treated", "treated", "treated"],    "mass_mg": [12.0, 11.5, 14.5, None, 14.0],    "conc_ugml": ["4.0", "3.5", "n/a", "5.0", "6.0"],})

1. Mean of one column (a Series)

df["mass_mg"].mean()

Result: 13.0. Series.mean has the same arguments as the DataFrame method, but axis is unused for a Series and the return value is a scalar. The missing value in row S4 was skipped, so the result is the mean of four numbers: (12.0 + 11.5 + 14.5 + 14.0) / 4.

2. Decide how missing values are handled

df["mass_mg"].mean(skipna=False)

Result: nan. With skipna=False a single missing value makes the whole mean missing. The documentation defines skipna as “exclude NA/null values when computing the result” and sets the default to True. Choose skipna=False when a missing value should stop you rather than be silently ignored. Either way, count what was dropped: df["mass_mg"].isna().sum() (see pandas isna), and consider whether rows should be removed explicitly with dropna.

3. Convert text columns before averaging

Calling df.mean() on the whole frame fails here because the text columns are not numeric. On pandas 3.1.1 the call raised TypeError: Cannot perform reduction 'mean' with string dtype. Convert the numeric-looking column first with pandas.to_numeric:

df["conc_ugml"] = pd.to_numeric(df["conc_ugml"], errors="coerce")df["conc_ugml"].isna().sum()

Result: 1. The documentation states that errors="raise" (the default) raises a ValueError on invalid parsing, while errors="coerce" sets invalid values to NaN. Coercion is convenient, but it hides which values were bad; the count above is the check that “n/a” was the only casualty.

4. Mean of several columns

df[["mass_mg", "conc_ugml"]].mean()

Result, a Series indexed by column name with dtype float64:

mass_mg      13.000conc_ugml     4.625

5. Mean across rows (axis=1)

df[["mass_mg", "conc_ugml"]].mean(axis=1)

Result: 8.0, 7.5, 14.5, 5.0, 10.0 for rows 0 to 4. The default axis=0 (also written axis="index") averages down each column; axis=1 (axis="columns") averages across the columns of each row. Row-wise means only make sense when the columns share a unit or scale, as with repeated measurements of the same quantity. Averaging milligrams with micrograms per millilitre, as this demonstration does for illustration, is not meaningful in real analysis. Rows with a missing value (S3 and S4 each have one) are averaged over the values that remain.

6. One mean over the whole frame (axis=None)

df[["mass_mg", "conc_ugml"]].mean(axis=None)

Result: 8.8125, the mean of all seven non-missing numbers. The documentation notes that axis=None applies the reduction across both axes and was added in version 2.0.0.

7. Skip non-numeric columns on purpose

df.mean(numeric_only=True)

The numeric_only argument is documented as “Include only float, int, boolean columns”, defaults to False, and the official example sets it to True “to avoid getting an error” when a text column is present. Use it when you knowingly want to ignore text columns, not as a way to silence an error you have not understood.

8. Group means

df.groupby("group")[["mass_mg", "conc_ugml"]].mean()

Result:

         mass_mg  conc_ugmlgroupcontrol    11.75       3.75treated    14.25       5.50

Group means are the most common research use of the method. Note that the treated mass mean (14.25) comes from two values because S4 is missing. For several statistics at once, see pandas agg.

The arguments, with documented defaults

Argument Default What the documentation says
axis 0 Accepts index (0) or columns (1). axis=None applies the reduction to both axes (added in version 2.0.0). Unused for a Series.
skipna True Exclude NA/null values when computing the result.
numeric_only False Include only float, int and boolean columns.
**kwargs none Additional keywords have no effect; they exist for NumPy compatibility.

The method returns a Series (for a DataFrame with the default axis) or a scalar.

Output and how to read it

A DataFrame mean() returns a Series whose index is the column labels (or the row labels with axis=1), with floating-point values. A Series mean() returns a single number. Means print in float format even when the inputs were integers: the official example pd.Series([1, 2, 3]).mean() returns 2.0.

The related method describe() reports the mean next to other summaries. For numeric columns its result index is count, mean, std, min, 25%, 50%, 75% and max. On the example data it shows why the missing value matters:

       mass_mg  conc_ugmlcount  4.00000   4.000000mean  13.00000   4.625000std    1.47196   1.108678min   11.50000   3.50000025%   11.87500   3.87500050%   13.00000   4.50000075%   14.12500   5.250000max   14.50000   6.000000

Always read count beside mean: both columns have five rows but only four contributed to the mean. Report the number of observations behind each mean in a paper’s methods or results tables rather than the row count of the file.

Troubleshooting

TypeError when calling df.mean()

Cause: at least one column is not numeric, so the mean cannot be computed. Fix: select the numeric columns, convert with pd.to_numeric, or pass numeric_only=True if ignoring those columns is what you intend. Check column types with df.dtypes first.

ValueError from pd.to_numeric

Cause: the default errors="raise" stops on the first value that cannot be parsed (for example "n/a" or a number with a unit attached). Fix: clean the strings, or use errors="coerce" and then check how many values became NaN.

The result is nan

Cause: either every value in the column is missing, or you passed skipna=False and there is at least one missing value. Fix: inspect with isna().sum() and decide whether to drop or impute upstream.

The mean looks wrong after coercion

Cause: errors="coerce" turned unparseable values into NaN, which mean() then skips, so the average describes fewer observations than you expect. Fix: compare the NaN count before and after conversion.

A row-wise mean mixes units

Cause: axis=1 averages every selected column, whatever it measures. Fix: select only the columns that share a unit, as in step 5.

Free alternatives

pandas is free, open-source software. The same calculation exists in other free tools; the data table below compares how the official documentation of each describes its mean function. Choose by the language your analysis already uses, not by the mean itself, which is the same quantity in each. See also NumPy mean for the array version in more detail.

Tool Call Notes from the official documentation
NumPy numpy.mean(a, axis=None, dtype=None, out=None, keepdims=..., *, where=...) Default axis=None averages the flattened array. Integer input defaults to a float64 computation. For float32 input the page warns that precision can be poor and suggests the dtype argument. nanmean is listed under See also.
Polars DataFrame.mean() Aggregates each column to its mean and returns a one-row DataFrame; in the documentation example a string column returns null.
R (base) mean(x, trim = 0, na.rm = FALSE, ...) na.rm = TRUE removes NA values first; trim drops a fraction (0 to 0.5) of observations from each end before averaging; non-numeric input returns NA with a warning.

Note the opposite defaults for missing values: pandas skips them unless told otherwise, while base R’s mean returns NA unless na.rm = TRUE. This is the most common source of different answers when the same data are analysed in both languages.

FAQ

How do I get the mean of a column in pandas?

Select the column and call mean(): df["column_name"].mean(). The result is a single float, and missing values are skipped by default.

How do I get the mean of every column?

Call df.mean() on a frame that contains only numeric columns, or df.mean(numeric_only=True) to ignore text columns. The result is a Series with one value per column.

How do I calculate the mean of each row?

Use df.mean(axis=1) on the numeric columns that share a unit.

Does pandas mean ignore NaN?

Yes by default, because skipna=True. Set skipna=False if a missing value should make the result NaN.

What is the difference between pandas mean and NumPy mean?

The pandas method works on labelled Series and DataFrames, averages down columns by default and skips missing values by default. numpy.mean works on arrays and averages the flattened array by default.

How do I calculate the mean per group?

Use df.groupby("group")[["col_a", "col_b"]].mean(), as in step 8.

Sources

Data: Mean function signatures and missing-value defaults: pandas, NumPy, Polars and R

Compares the documented signature, default scope and missing-value control of the mean function in pandas, NumPy, Polars and base R, compiled from each project's official reference documentation.

Period covered: 2026.

Mean function signatures and missing-value defaults: pandas, NumPy, Polars and R
ToolDocumented callDefault scopeMissing-value control
pandas 3.1.1DataFrame.mean(*, axis=0, skipna=True, numeric_only=False, **kwargs)axis=0: one mean per columnskipna=True (NA/null excluded)
NumPy 2.5numpy.mean(a, axis=None, dtype=None, out=None, keepdims=, *, where=)axis=None: mean of the flattened arrayNo NaN argument in the signature (nanmean is listed under See also)
PolarsDataFrame.mean()Each column aggregated to its mean, one-row DataFrameNo argument in the signature
R basemean(x, trim = 0, na.rm = FALSE, ...)A single vector xna.rm = FALSE (set TRUE to remove NA)

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

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

Ask CASRAI · free to try

Ask about pandas mean: DataFrame.mean() Syntax, Examples and Errors

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

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 open 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 →