How do you calculate the mean or average of a column in Pandas? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you calculate the mean or average of a column in Pandas?

message-square
0

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=True when calling df.mean() on an entire DataFrame:
    • In Pandas 2.0+, calling df.mean() without arguments on a DataFrame containing string (object or string) columns raises TypeError: Could not convert string '...' to numeric. Pass df.mean(numeric_only=True) (or filter via df.select_dtypes(include="number").mean()) so non-numeric columns are cleanly skipped.
  • How missing values (NaN) affect .mean() (skipna=True vs. skipna=False):
    • By default (skipna=True), [88.0, 92.0, NaN, 90.0] divides by 3 (non-null entries), returning 90.0.
    • Pass skipna=False (df["score"].mean(skipna=False)) if any missing entry should yield NaN, or chain .fillna(0).mean() if missing values should count as 0 in the denominator (270 / 4 = 67.5).
  • Empty or all-NaN columns:
    • Calling .mean() on an empty Series or an all-NaN column returns np.nan without raising an exception.
  • Row-wise average across columns (axis=1) vs. column-wise average (axis=0):
    • .mean() defaults to axis=0 (down each column). Pass axis=1 to 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().
  • Weighted averages (np.average):
    • Pandas .mean() computes an unweighted arithmetic mean; for a weighted average, drop paired NaN values first and pass weights to NumPy: valid = df.dropna(subset=["score", "weight"]); weighted_avg = np.average(valid["score"], weights=valid["weight"]).

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.