Sub topic 9
Summarising columns with describe and reductions
This chapter assumes you can create a DataFrame, select columns, and tell a Series from a DataFrame. It uses the sales table from earlier chapters.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})Reductions
A reduction collapses a column into one number. Common ones are sum, mean, median, min, max, std and count.
print(df["units"].sum()) # 42.0
print(df["units"].mean()) # 8.4
print(df["units"].median()) # 8.0
print(df["units"].count()) # 5
print(len(df)) # 6count returns the number of non-missing values. len(df) returns the number of rows. They differ here because one units value is missing.
Missing values are skipped by default. The mean above is 42 divided by 5, not by 6. Pass skipna=False to make a missing value poison the result:
print(df["units"].mean(skipna=False)) # nanSeveral statistics at once
The agg method accepts a list of function names. On a Series it returns a Series. On a DataFrame it returns one column per input column.
print(df["units"].agg(["sum", "mean", "median"]))
print(df[["units", "price"]].agg(["min", "max", "mean"]))To compute different statistics for different columns, pass a dictionary. Statistics that were not requested for a column appear as NaN.
print(df.agg({"units": ["sum", "mean"], "price": ["min", "max"]}))describe
describe bundles the most common statistics into one call. For a numeric column it reports count, mean, std, min, the quartiles (25%, 50%, 75%) and max.
print(df["units"].describe())For units, the count is 5, the mean is 8.4, the minimum is 5 and the maximum is 12. The 50% row is the median, 8.0.
Called on a whole DataFrame, describe includes only numeric columns. Use include to change that:
print(df.describe())
print(df.describe(include="all"))
print(df.describe(percentiles=[0.1, 0.9]))With include="all", text columns get count, unique, top and freq instead. Rows that do not apply to a column are filled with NaN. The percentiles argument replaces the default quartiles. The median is always kept.
Common errors
- Reading count as the row count.
countignores missing values. Uselen(df)orsizewhen you want every row. - Summing text columns.
df["region"].sum()concatenates the strings. Select numeric columns first, or passnumeric_only=Truewhen reducing a DataFrame. - Forgetting that
stdis the sample standard deviation. It divides by n - 1 (ddof=1). Passddof=0for the population version. - Trusting the mean on skewed data. Compare
meanwith the50%row. A large gap suggests outliers.
Exercise
A Series is built with pd.Series([4, None, 8]). What do its mean() and count() return, and what does mean(skipna=False) return?
Show answer
mean() returns 6.0 because the missing value is skipped and (4 + 8) / 2 = 6. count() returns 2 because only two values are present. mean(skipna=False) returns nan because the missing value is included in the calculation.