Sub topic 5
Turning counts into proportions
This chapter assumes you can build a Series and DataFrame, select a column, and call value_counts as covered in the previous chapter. It focuses on the normalize argument. It also covers the denominator that normalize uses, which changes when missing values are present.
What normalize does
value_counts(normalize=True) divides each count by the total of the counts. The result holds fractions between 0 and 1 that add up to 1. The order is unchanged: the most frequent value still comes first.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
counts = df["city"].value_counts()
shares = df["city"].value_counts(normalize=True)
print(counts) # Oslo 3, Rome 2, Paris 1
print(shares) # Oslo 0.500000, Rome 0.333333, Paris 0.166667The later examples in this chapter reuse this df.
The three shares add up to 1 because the denominator is 6, the number of non-missing cities. The missing value is not in the table and not in the denominator.
The denominator and missing values
By default value_counts drops missing values before it counts anything. normalize=True divides by what is left, so the proportions describe "of the rows that have a city". Passing dropna=False keeps the missing value as its own row and adds it to the denominator.
with_missing = df["city"].value_counts(normalize=True, dropna=False)
print(with_missing["Oslo"]) # 3 / 7, about 0.4286 (it was 0.5 with the default)
print(with_missing.sum()) # 1.0 (up to floating-point error)The same city now has a different share. Neither answer is wrong, because they answer different questions:
| Call | Denominator | Question it answers |
|---|---|---|
| `value_counts(normalize=True)` | 6 non-missing cities | Among customers who gave a city, what share live in Oslo? |
| `value_counts(normalize=True, dropna=False)` | 7 rows | Among all customers, what share live in Oslo, and what share gave no city? |
When you report a proportion, decide which question you are answering and say so. A "50% of users are in Oslo" claim is misleading if one in seven users has no city and the reader assumes all seven are in the denominator.
Computing proportions by hand
normalize=True is shorthand for dividing the counts by their sum. Doing it yourself lets you pick any denominator you like.
manual = counts / counts.sum() # same values as normalize=True
of_all_rows = counts / len(df) # denominator 7, but the missing row is not listed
print(manual.equals(shares)) # True, apart from the Series name in pandas 2.x
print(of_all_rows.sum()) # 6/7, about 0.857, because the missing row is not listedThe second line shows a useful pattern. You get shares of all rows while the missing value stays out of the table, so the listed shares add up to less than 1. The gap is the share of missing values. If you want that gap visible as a number, use dropna=False instead.
Use manual.equals(shares) with care. In pandas 2.0 and later, value_counts names its result "count" or "proportion", and Series.equals ignores names, so it compares only values and index. Use pd.testing.assert_series_equal(..., check_names=False) if you want a stricter check with a clear error message.
Percentages and rounding
Multiply by 100 for percentages, and round only at the end, when you present the numbers.
pct = (shares * 100).round(1)
print(pct) # Oslo 50.0, Rome 33.3, Paris 16.7
print(pct.sum()) # 100.0 here, but rounding does not always sum to 100Rounded values can fail to add up. Three equal groups each get 33.3, and the total is about 99.9.
equal = pd.Series(list("abc")).value_counts(normalize=True)
print((equal * 100).round(1).sum()) # about 99.9, not 100This is not a pandas bug. Rounded numbers only approximate the exact fractions. Keep the unrounded Series for any further calculation, and round a copy for display. For the same reason, check that shares sum to 1 with math.isclose(shares.sum(), 1.0) and not with ==.
Getting a table with named columns
Often you want a DataFrame, not a Series, so that you can merge it, sort it or write it out. reset_index turns the labels back into a column.
table = df["city"].value_counts(normalize=True).reset_index()
print(table.columns.tolist()) # ['city', 'proportion'] in pandas 2.xThe column names depend on the pandas version. In pandas 2.0 and later the result is named proportion (or count without normalize) and the index keeps the column name city. In pandas 1.x the Series was named city and the index was unnamed, so reset_index produced columns called index and city. If your code must run on both, rename the columns explicitly after reset_index.
Proportions within groups
value_counts is also available on grouped Series. With normalize=True, each group is divided by its own total, so the shares sum to 1 inside each group, not across the whole table.
within_plan = df.groupby("plan")["city"].value_counts(normalize=True)
print(within_plan)
# plan city
# free Oslo 1.00 (2 of the 2 free rows that have a city)
# pro Rome 0.50
# Oslo 0.25
# Paris 0.25Pay attention to the free group. It has three rows, but one city is missing, so the denominator is 2 and Oslo gets 1.0. This is the same non-missing denominator rule as before, applied per group.
This differs from df.value_counts(["plan", "city"], normalize=True), which divides every pair by one overall total. Use the grouped form for "within each plan, what share is each city" and the DataFrame form for "what share of all rows is each combination".
Proportions of column combinations
DataFrame.value_counts accepts normalize as well. It drops rows with a missing value in any listed column by default, so the denominator is the number of complete rows.
combo = df.value_counts(["city", "plan"], normalize=True)
print(combo)
# city plan
# Oslo free 0.333333 (2 of 6 complete rows)
# Rome pro 0.333333
# Oslo pro 0.166667
# Paris pro 0.166667Here the row with a missing city is dropped, so the denominator is 6, not 7. If you need the row counted, pass dropna=False. The crosstab function can normalize a table by rows, by columns, or by the grand total (normalize="index", "columns" or "all"). A later chapter covers it.
Edge cases
- Empty or all-missing input. With the default
dropna=True, a Series that holds only missing values yields an empty result. Nothing is divided by zero, but there is nothing to report either, so checklen(result)before indexing into it. - Numeric columns.
value_counts(normalize=True)on floats treats each distinct float as one value. Fractions computed this way are rarely useful until you group the values into bins, which a later chapter covers. - Looking up one share.
shares["Oslo"]raisesKeyErrorif the value does not occur. Useshares.get("Oslo", 0.0)when a value might be absent. - Sorting. The result is sorted by proportion, highest first. Use
sort=Falseorsort_index()for another order, as covered in the chapter on ordering.
Exercise
Using the df from this chapter, what does df["city"].value_counts(normalize=True, dropna=False)["Oslo"] return, and why is it different from the share you get without dropna=False?
Show answer
It returns 3/7, about 0.4286. With dropna=False the missing city is kept as an entry, so the denominator is all 7 rows. Without it, the denominator is the 6 non-missing cities, and the share is 3/6 = 0.5.
Exercise
How would you get the share of each plan value among all rows, then the same shares as percentages rounded to one decimal place?
Show answer
shares = df["plan"].value_counts(normalize=True) gives pro 4/7 and free 3/7, because the plan column has no missing values. Then pct = (shares * 100).round(1) gives pro 57.1 and free 42.9.
Exercise
You run df.groupby("plan")["city"].value_counts(normalize=True) and see Oslo = 1.0 for the free plan, although free has three rows. Why?
Show answer
One of the three free rows has a missing city. It is dropped before counting, so the denominator for the group is 2, and both remaining rows are Oslo. Oslo's share is 2/2 = 1.0.