Descriptive Statistics
Descriptive statistics summarise a column in a few numbers: its total, its average, how spread out it is. pandas has a method for each of them, and they all share the same conventions: they skip missing values and work per column on a DataFrame.
Common aggregation methods
| Method | Result |
|---|---|
count() |
number of non-missing values |
sum() |
total |
mean() / median() |
average / middle value |
min() / max() |
smallest / largest |
std() / var() |
standard deviation / variance |
quantile(q) |
value below which a fraction q of the data lies |
mode() |
most frequent value(s) |
prod() |
product of all values |
cumsum(), cummax(), … |
running totals and maxima |
import pandas as pd
rainfall = pd.Series([12.0, 0.0, 3.5, 22.1, 0.0, 8.4, 15.0], name="mm",
index=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
print("total :", rainfall.sum())
print("mean :", round(rainfall.mean(), 2))
print("median:", rainfall.median())
print("max :", rainfall.max(), "on", rainfall.idxmax())
print("std :", round(rainfall.std(), 2))
print("dry days:", (rainfall == 0).sum())total : 61.0
mean : 8.71
median: 8.4
max : 22.1 on Thu
std : 8.25
dry days: 2
Statistics on a DataFrame
On a DataFrame each method returns one value per column. With axis=1 (or axis="columns") it works across each row instead:
import pandas as pd
exams = pd.DataFrame({
"math": [78, 92, 65, 88],
"physics": [82, 85, 70, 91],
"art": [95, 60, 88, 74],
}, index=["Lena", "Marc", "Nia", "Otto"])
print(exams.mean())
print(exams.mean(axis=1).round(1))
print(exams.max(axis=1))
print(exams.idxmax(axis=1))math 80.75
physics 82.00
art 79.25
dtype: float64
Lena 85.0
Marc 79.0
Nia 74.3
Otto 84.3
dtype: float64
Lena 95
Marc 92
Nia 88
Otto 91
dtype: int64
Lena art
Marc math
Nia art
Otto physics
dtype: object
exams.mean() is the average per subject (down each column); exams.mean(axis=1) is the average per student (across each row).
Mean versus median
The mean is pulled toward extreme values; the median isn't. Comparing the two tells you whether a few outliers dominate:
import pandas as pd
salaries = pd.Series([2400, 2600, 2550, 2700, 2450, 2500, 19000])
print("mean :", round(salaries.mean(), 1))
print("median:", salaries.median())
print("mean without the top value:", round(salaries.nsmallest(6).mean(), 1))mean : 4885.7
median: 2550.0
mean without the top value: 2533.3
One very high salary lifts the mean far above what a typical person earns, while the median stays near the middle.
Quantiles and spread
import pandas as pd
load_ms = pd.Series([120, 135, 128, 410, 142, 131, 125, 980, 138, 133])
print(load_ms.quantile([0.5, 0.9, 0.95]))
print("range:", load_ms.max() - load_ms.min())
print("IQR :", load_ms.quantile(0.75) - load_ms.quantile(0.25))0.50 134.0
0.90 467.0
0.95 723.5
dtype: float64
range: 860
IQR : 12.25
Percentiles such as p90 and p95 are how engineers describe response times: "95% of page loads finish within this many milliseconds."
Several statistics at once with agg()
agg() applies a list of functions and returns them in one table:
import pandas as pd
exams = pd.DataFrame({
"math": [78, 92, 65, 88],
"physics": [82, 85, 70, 91],
"art": [95, 60, 88, 74],
})
print(exams.agg(["min", "max", "mean", "median"]))
print(exams.agg({"math": ["mean", "std"], "art": "max"}).round(2)) math physics art
min 65.00 70.0 60.00
max 92.00 91.0 95.00
mean 80.75 82.0 79.25
median 83.00 83.5 81.00
math art
mean 80.75 NaN
std 12.04 NaN
max NaN 95.0
With a dictionary, each column gets its own list of functions; cells for combinations you didn't ask for (such as the std of art) are NaN.
Running totals
Cumulative methods return a Series of the same length, building up as they go:
import pandas as pd
deposits = pd.Series([200, 50, -120, 300, -80], name="change")
print(pd.DataFrame({
"change": deposits,
"balance": deposits.cumsum(),
"peak": deposits.cumsum().cummax(),
})) change balance peak
0 200 200 200
1 50 250 250
2 -120 130 250
3 300 430 430
4 -80 350 430
Note: Use
skipna=Falseif you want a missing value to make the result NaN instead of being skipped:s.sum(skipna=False).
Test yourself
What does df.mean(axis=1) compute?
- The mean of each column
- The mean of each row
- The mean of the whole table
- The mean of the index
A column has values 1, 2, 3, 4, 100. Which statistic best describes a typical value?
- mean
- median
- max
- sum
What does s.cumsum() return for [1, 2, 3]?
- 6
- [1, 3, 6]
- [1, 2, 3]
- [6, 5, 3]