Frequency Tables
A frequency table lists each value (or group of values) together with how often it occurs. It is the simplest way to turn a long list of raw data into something readable, and it is the foundation for bar charts, histograms and pie charts.
Counting categories
A bike-rental shop logged the type of the last 20 bikes rented:
from collections import Counter
rentals = ["city", "e-bike", "city", "mountain", "city", "e-bike", "kids",
"city", "e-bike", "e-bike", "city", "mountain", "city", "e-bike",
"kids", "city", "e-bike", "city", "mountain", "e-bike"]
freq = Counter(rentals)
print(f"{'type':10s} {'freq':>4s}")
for bike, count in freq.most_common():
print(f"{bike:10s} {count:4d}")
print(f"{'total':10s} {sum(freq.values()):4d}")type freq
city 8
e-bike 7
mountain 3
kids 2
total 20
Relative and cumulative frequency
A frequency table usually has more columns than raw counts:
| Column | Formula | Meaning |
|---|---|---|
Frequency f |
count | how many times the value occurs |
| Relative frequency | f / n |
the share of all observations (adds up to 1, or 100%) |
| Cumulative frequency | running total of f |
how many observations are at or below this value |
| Cumulative relative frequency | running total of f / n |
the share at or below this value |
Cumulative columns only make sense when the values have an order. Here are the numbers of children per household in a survey of 25 households:
from collections import Counter
children = [2, 0, 1, 3, 2, 1, 0, 2, 4, 1, 2, 2, 0, 1, 3,
2, 1, 0, 2, 1, 5, 2, 1, 3, 2]
n = len(children)
freq = Counter(children)
print("value f rel.f cum.f cum.rel")
cum = 0
for value in sorted(freq):
f = freq[value]
cum += f
print(f"{value:5d} {f:2d} {f / n:5.2f} {cum:5d} {cum / n:7.2f}")value f rel.f cum.f cum.rel
0 4 0.16 4 0.16
1 7 0.28 11 0.44
2 9 0.36 20 0.80
3 3 0.12 23 0.92
4 1 0.04 24 0.96
5 1 0.04 25 1.00
Reading the last column: 80% of the households (cumulative relative frequency 0.80 at value 2) have two children or fewer.
Frequency tables with pandas
value_counts() builds the table in one line. Add normalize=True for relative frequencies:
import pandas as pd
children = pd.Series([2, 0, 1, 3, 2, 1, 0, 2, 4, 1, 2, 2, 0, 1, 3,
2, 1, 0, 2, 1, 5, 2, 1, 3, 2])
table = pd.DataFrame({"f": children.value_counts().sort_index()})
table["rel_f"] = (table["f"] / table["f"].sum()).round(2)
table["cum_f"] = table["f"].cumsum()
table["cum_rel_f"] = (table["cum_f"] / table["f"].sum()).round(2)
print(table) f rel_f cum_f cum_rel_f
0 4 0.16 4 0.16
1 7 0.28 11 0.44
2 9 0.36 20 0.80
3 3 0.12 23 0.92
4 1 0.04 24 0.96
5 1 0.04 25 1.00
Grouped frequency tables
Continuous data, like commute times, rarely repeats exactly, so we group values into classes (also called bins or intervals) of equal width. Here are the one-way commute times in minutes of 40 employees, a dataset we will reuse through this section:
import pandas as pd
commute = [22, 35, 18, 41, 27, 30, 25, 52, 33, 29, 19, 24, 38, 31, 27, 45, 23, 28, 36, 26,
21, 34, 30, 58, 27, 32, 25, 29, 40, 24, 17, 31, 28, 37, 26, 33, 22, 30, 47, 28]
classes = pd.cut(pd.Series(commute), bins=range(10, 70, 10), right=False)
table = classes.value_counts().sort_index().to_frame("f")
table["rel_f"] = table["f"] / len(commute)
table["cum_f"] = table["f"].cumsum()
print(table) f rel_f cum_f
[10, 20) 3 0.075 3
[20, 30) 18 0.450 21
[30, 40) 13 0.325 34
[40, 50) 4 0.100 38
[50, 60) 2 0.050 40
right=False makes each class include its left edge and exclude its right edge: [20, 30) contains 20 up to 29.99. Being explicit about edges avoids counting a value of exactly 30 twice, or not at all.
Choosing classes
- Use equal widths, with "nice" edges (5, 10, 20…).
- Aim for roughly 5–15 classes. Too few hide the shape; too many leave lots of classes with 0 or 1 value. A common starting point is about
√nclasses. - Classes must not overlap and must cover all values.
Frequency tables for two variables
A contingency table (cross-table) counts combinations of two categorical variables. It is the basis of the Chi-Square Test:
import pandas as pd
rentals = pd.DataFrame({
"bike": ["city", "e-bike", "city", "mountain", "city", "e-bike", "city", "e-bike"],
"day": ["weekday", "weekend", "weekday", "weekend", "weekend", "weekday", "weekday", "weekend"],
})
print(pd.crosstab(rentals["bike"], rentals["day"], margins=True))day weekday weekend All
bike
city 3 1 4
e-bike 1 2 3
mountain 0 1 1
All 4 4 8
Test yourself
In a survey of 50 people, 12 chose 'tea'. What is the relative frequency of 'tea'?
- 12
- 0.12
- 0.24
- 0.50
The cumulative frequency for the value 3 is 41. What does that mean?
- 41 observations equal 3
- 41 observations are 3 or less
- 41% of observations are above 3
- The value 3 appears 41% of the time
Why are grouped classes like [20, 30) used for continuous data?
- Because continuous values rarely repeat, so counting each exact value is useless
- Because pandas can't count decimals
- To make the mean larger
- Because classes are required for categorical data