mean() shares sum()'s default axis and skipna behavior, but divides by the count of non-null values rather than the total row count, so a column's mean is computed only over the values that are actually present. Calling mean() directly on a DataFrame with non-numeric columns can raise an error, or, depending on the pandas version, silently skip them, which is why numeric_only=True is sometimes needed explicitly to restrict the calculation to columns where a mean actually makes sense.
1Understanding df.mean()
mean() shares sum()'s default axis and skipna behavior, but divides by the count of non-null values rather than the total row count, so a column's mean is computed only over the values that are actually present. Calling mean() directly on a DataFrame with non-numeric columns can raise an error, or, depending on the pandas version, silently skip them, which is why numeric_only=True is sometimes needed explicitly to restrict the calculation to columns where a mean actually makes sense.
Pass numeric_only=True when calling mean(), or similar aggregations, directly on a DataFrame that has non-numeric columns mixed in — otherwise the call can raise an error, or its behavior can vary depending on the pandas version, since a mean isn't meaningful for text columns.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
print(df.mean())2Practical Example
Here is a real-world application of df.mean() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"team": ["A", "A", "B"], "score": [10, 20, 30]})
print(df.groupby("team")["score"].mean())3Best Practices
Follow these guidelines when working with df.mean():
1. Chain mean() after groupby() for per-group averages, the pandas equivalent of a SQL GROUP BY with AVG()
2. Pass numeric_only=True when calling mean() on a DataFrame that mixes numeric and non-numeric columns
3. Be aware NaN values are excluded from both the sum and the count used to compute the mean by default, rather than treated as 0
Tip: Pass numeric_only=True when calling mean(), or similar aggregations, directly on a DataFrame that has non-numeric columns mixed in — otherwise the call can raise an error, or its behavior can vary depending on the pandas version, since a mean isn't meaningful for text columns.
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
print(df.mean())