Select the column and call .mean()—for example, df["score"].mean() for a single column or df[["score", "hours"]].mean() for multiple columns—which automatically skips NaN/None missing values by default (skipna=True) and returns a scalar float for one column or a pd.Series indexed by column name for multiple columns.
Basic Example
import pandas as pd
df = pd.DataFrame({
"student": ["Ali", "Sara", "Bilal", "Zara"],
"score": [88.0, 92.0, None, 90.0],
"hours": [5, 7, 4, 8],
})
# 1. Recommended: Single column mean (ignores `None`/`NaN` automatically)
avg_score = df["score"].mean()
print(avg_score)
# Output: 90.0
# 2. Mean across multiple selected numeric columns (returns a Series):
print(df[["score", "hours"]].mean())
# Output:
# score 90.0
# hours 6.0
# dtype: float64
# 3. Mean across ALL numeric columns safely when string columns are present:
print(df.mean(numeric_only=True))
# Output:
# score 90.0
# hours 6.0
# dtype: float64
Key Details & Edge Cases
- Always pass
numeric_only=Truewhen callingdf.mean()on an entire DataFrame:- In Pandas 2.0+, calling
df.mean()without arguments on a DataFrame containing string (objectorstring) columns raisesTypeError: Could not convert string '...' to numeric. Passdf.mean(numeric_only=True)(or filter viadf.select_dtypes(include="number").mean()) so non-numeric columns are cleanly skipped.
- In Pandas 2.0+, calling
- How missing values (
NaN) affect.mean()(skipna=Truevs.skipna=False):- By default (
skipna=True),[88.0, 92.0, NaN, 90.0]divides by3(non-null entries), returning90.0. - Pass
skipna=False(df["score"].mean(skipna=False)) if any missing entry should yieldNaN, or chain.fillna(0).mean()if missing values should count as0in the denominator (270 / 4 = 67.5).
- By default (
- Empty or all-
NaNcolumns:- Calling
.mean()on an empty Series or an all-NaNcolumn returnsnp.nanwithout raising an exception.
- Calling
- Row-wise average across columns (
axis=1) vs. column-wise average (axis=0):.mean()defaults toaxis=0(down each column). Passaxis=1to compute each row’s average across multiple columns:df["row_avg"] = df[["exam_1", "exam_2", "exam_3"]].mean(axis=1)
- Grouped column averages (
groupby(...).mean()):- Compute per-group averages cleanly with
df.groupby("department", as_index=False)["salary"].mean().
- Compute per-group averages cleanly with
- Weighted averages (
np.average):- Pandas
.mean()computes an unweighted arithmetic mean; for a weighted average, drop pairedNaNvalues first and pass weights to NumPy:valid = df.dropna(subset=["score", "weight"]); weighted_avg = np.average(valid["score"], weights=valid["weight"]).
- Pandas
Comparison of Column-Averaging Methods in Pandas / NumPy
| Method | Skips NaN by Default? |
Return Type | Safe on Mixed String + Numeric DataFrames? | Best Used When |
|---|---|---|---|---|
df["col"].mean() (Recommended) |
Yes (skipna=True) |
float scalar |
N/A (targets single numeric column) | Computing the arithmetic mean of a single column. |
df[["col1", "col2"]].mean() |
Yes (skipna=True) |
pd.Series |
Yes (when selecting numeric columns) | Computing averages for a specific list of numeric columns at once. |
df.mean(numeric_only=True) |
Yes (skipna=True) |
pd.Series |
Yes (ignores text/categorical columns) | Summarizing averages across every numeric column in a DataFrame. |
df.groupby("grp")["col"].mean() |
Yes (skipna=True) |
pd.Series (or DataFrame with as_index=False) |
Yes | Calculating category-level averages across groups. |
np.average(s, weights=w) |
No (propagates NaN if present) |
float scalar |
N/A (1D numeric arrays/Series only) | Computing weighted averages where rows carry unequal weights. |
You must log in or register to comment.
