pandas
data analysis
mean calculation
data manipulation
python pandas

pandas get column average/mean

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

In pandas, the average of a column is usually just df["column"].mean(). That simple call hides a few important behaviors, though: pandas skips missing values by default, returns a scalar for a single Series, and becomes much more powerful once you combine mean() with filtering, grouping, or rolling windows.

Mean Of One Column

For a single numeric column, call mean() on the Series:

python
1import pandas as pd
2
3df = pd.DataFrame({
4    "name": ["Alice", "Bob", "Charlie", "Diana"],
5    "score": [85, 92, 78, 96],
6})
7
8avg_score = df["score"].mean()
9print(avg_score)

This is the most direct answer to the title. The return value is a scalar number, not another DataFrame.

The dot-access form also works if the column name is a valid attribute:

python
print(df.score.mean())

But bracket access is usually safer because it works with all column names.

Missing Values Are Ignored By Default

Pandas skips NaN values unless you tell it not to:

python
1df = pd.DataFrame({
2    "score": [10, 20, None, 40]
3})
4
5print(df["score"].mean())               # 23.333...
6print(df["score"].mean(skipna=False))   # nan

That default is often helpful, but it can also hide the fact that a large part of the column is missing. When the average matters, it is worth checking the null count too:

python
print(df["score"].isna().sum())

Filter First, Then Average

Many real questions are conditional: "what is the average score for product A?" or "what is the mean where quantity is positive?"

python
1df = pd.DataFrame({
2    "product": ["A", "B", "A", "B", "A"],
3    "price": [10, 20, 15, 25, 12],
4})
5
6avg_price_a = df.loc[df["product"] == "A", "price"].mean()
7print(avg_price_a)

That pattern is one of the most common pandas idioms: use .loc[...] to narrow the rows, then call mean() on the target column.

Grouped Means

If you need an average per category, use groupby.

python
1df = pd.DataFrame({
2    "department": ["Engineering", "Engineering", "Sales", "Sales"],
3    "salary": [120000, 130000, 80000, 85000],
4})
5
6result = df.groupby("department")["salary"].mean()
7print(result)

That returns a Series indexed by the group labels. If you want a DataFrame shape instead, reset the index:

python
result = df.groupby("department", as_index=False)["salary"].mean()
print(result)

Grouped means are especially useful in reports, dashboards, and feature engineering pipelines.

Convert Text To Numbers Before Averaging

One of the most common reasons mean() fails is that the column looks numeric to a human but is actually stored as strings. In that case, convert it first:

python
1import pandas as pd
2
3df = pd.DataFrame({
4    "revenue": ["100", "250", "bad", "400"]
5})
6
7df["revenue"] = pd.to_numeric(df["revenue"], errors="coerce")
8avg_revenue = df["revenue"].mean()
9
10print(df)
11print(avg_revenue)

Using errors="coerce" turns invalid values into NaN, which pandas will then skip by default. That is usually safer than crashing in the middle of an analysis pipeline, but it also means you should inspect bad rows if data quality matters.

Rolling And Weighted Averages

For time series, you may want a moving average rather than one global mean:

python
1df = pd.DataFrame({
2    "value": [10, 12, 8, 15, 11, 14, 9]
3})
4
5df["rolling_mean_3"] = df["value"].rolling(window=3).mean()
6print(df)

For weighted averages, pandas does not have a dedicated weighted_mean() method, so numpy.average is the usual tool:

python
1import numpy as np
2
3df = pd.DataFrame({
4    "grade": [90, 85, 95, 78],
5    "credits": [3, 4, 3, 2],
6})
7
8weighted_avg = np.average(df["grade"], weights=df["credits"])
9print(weighted_avg)

That distinction matters because a weighted average answers a different question from the ordinary arithmetic mean.

Common Pitfalls

  • Forgetting that mean() skips NaN values by default.
  • Calling mean() on the wrong column or on a mixed-type DataFrame without selecting numeric data deliberately.
  • Assuming a text column full of digits can be averaged without converting it to a numeric dtype first.
  • Using the mean when the distribution is dominated by outliers and the median would communicate the data better.
  • Forgetting that groupby(...).mean() changes the shape of the result.
  • Expecting pandas to provide a built-in weighted mean for every case.

Summary

  • Use df["column"].mean() for the average of one pandas column.
  • Missing values are ignored unless you pass skipna=False.
  • Filter with .loc[...] before calling mean() when the question is conditional.
  • Convert string data with pd.to_numeric(...) if the column is not already numeric.
  • Use groupby(...).mean() for per-category averages and rolling windows for moving averages.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.