Sub topic 11
Counting combinations of columns
This chapter assumes you can build a DataFrame, select columns, and have used Series.value_counts. You will count how often each combination of values occurs across several columns, and you will learn how that count treats missing values, ordering, and proportions.
From one column to several
Series.value_counts answers "how many times does each value appear?" for one column. Often the question involves two or more columns: how many customers are on each plan in each city? DataFrame.value_counts answers this. It treats each row (restricted to the columns you name) as one tuple and counts how many rows share the same tuple.
The examples in this chapter use this DataFrame:
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
pair_counts = df.value_counts(["city", "plan"])
print(pair_counts)The result is a Series with a MultiIndex, a row label made of several levels. Here the levels are city and plan, in the order you listed them. The values are the counts:
("Oslo", "free")appears 2 times (rows 0 and 2).("Rome", "pro")appears 2 times (rows 1 and 4).("Oslo", "pro")appears 1 time (row 5).("Paris", "pro")appears 1 time (row 3).
The counts add up to 6, not 7. Row 6 has a missing city, so it is left out. The next sections explain why.
Choosing the columns
The first argument, subset, picks the columns that form the tuple. It accepts a list of names or a single name.
df.value_counts(["city", "plan"])counts pairs.df.value_counts("plan")counts one column, so the index has a single level.df.value_counts()with no argument uses every column.
Without subset, adding a column to the DataFrame later silently changes what you count. If a column such as an ID is unique per row, every count becomes 1. Pass the columns explicitly in code you intend to keep.
The order of the names sets the order of the index levels. ["plan", "city"] gives the same counts with plan as the outer level.
DataFrame.value_counts was added in pandas 1.1. The dropna parameter arrived in 1.3.
Missing values
By default dropna=True. A row is excluded if any of the chosen columns is missing. This differs from Series.value_counts only in scope: one missing field removes the whole tuple, even if the other field has a value.
Set dropna=False to keep those rows. The tuple with the missing value becomes its own entry:
with_missing = df.value_counts(["city", "plan"], dropna=False)
print(with_missing)
print(with_missing.sum()) # 7, every row is countedYou now see (NaN, "free") with a count of 1, and the total matches len(df). Use dropna=False when you need to audit data quality, or when you want the counts to add up to the number of rows.
Proportions
normalize=True divides each count by the total and returns fractions:
shares = df.value_counts(["city", "plan"], normalize=True)
print(shares) # 0.333..., 0.333..., 0.166..., 0.166...
print(shares.sum()) # 1.0The denominator is the number of rows that were counted. With the default dropna=True that is 6, so ("Oslo", "free") is 2/6. With dropna=False it is 7, so the same pair becomes 2/7. State which one you mean when you report a percentage, because the difference can be large when many values are missing.
These are shares of all combinations. They are not shares within each city. To get the share of each plan inside each city, normalize per group. For example, pd.crosstab(df["city"], df["plan"], normalize="index") divides each row of the table by its own total. Crosstab gets its own chapter.
Ordering the result
The result is sorted by count, largest first. Two parameters control this:
sort=Falseskips sorting and returns the groups in the order the implementation produces them. Do not rely on that order.ascending=Trueputs the rarest combinations first.
Ties are the common trap. ("Oslo", "free") and ("Rome", "pro") both have a count of 2, and pandas does not promise which comes first. If a report or a test depends on a stable order, sort on the index as well:
stable = (
df.value_counts(["city", "plan"])
.rename("n")
.reset_index()
.sort_values(["n", "city", "plan"], ascending=[False, True, True])
.reset_index(drop=True)
)
print(stable)Calling reset_index() on a counted Series turns the index levels into ordinary columns and gives you a DataFrame with city, plan and n. Renaming the Series first with .rename("n") means the column name does not depend on your pandas version. Newer versions name it count by default and older ones used 0.
To order by the labels instead of the counts, use sort_index():
by_label = df.value_counts(["city", "plan"]).sort_index()Looking things up in the result
Because the result has a MultiIndex, .loc accepts partial and full keys:
pair_counts = df.value_counts(["city", "plan"])
print(pair_counts.loc[("Oslo", "free")]) # 2
print(pair_counts.loc["Oslo"]) # counts by plan for OsloA full tuple returns one number. A single outer label returns a smaller Series indexed by the remaining level. Asking for a combination that never occurs, such as ("Paris", "free"), raises a KeyError. Combinations with a count of zero are not stored. If you need them, reshape the result into a table:
table = df.value_counts(["city", "plan"]).unstack(fill_value=0)
print(table)unstack moves the inner index level (plan) into the columns. fill_value=0 fills the combinations that did not occur, such as Paris on the free plan. The result is a city-by-plan grid of counts. pd.crosstab produces the same grid directly from the two columns.
Using the counts to find duplicates
A combination that appears more than once is a repeated row on those columns. So the counts give a compact view of duplication:
repeated = pair_counts[pair_counts > 1]
print(repeated) # (Oslo, free) 2 and (Rome, pro) 2
extra_rows = (pair_counts - 1).sum()
print(extra_rows) # 2extra_rows is 2, which matches the number of rows df.duplicated(subset=["city", "plan"]) flags (rows 2 and 4). The two methods differ in how they treat missing values. duplicated treats two missing values as equal, so repeated rows with a missing city are flagged. value_counts drops those rows unless you pass dropna=False. If your duplicate count and your value_counts numbers disagree, check this first.
Comparison with groupby
You can get nearly the same numbers with groupby:
by_group = df.groupby(["city", "plan"]).size()The differences are small but matter:
| Aspect | `df.value_counts(cols)` | `df.groupby(cols).size()` |
|---|---|---|
| Default order | By count, descending | By group keys, ascending |
| Missing keys | Dropped, `dropna=False` keeps them | Dropped, `dropna=False` keeps them |
| Proportions | `normalize=True` | Divide by the total yourself |
| Extra aggregations | None, counts only | Can add `.agg(...)` on other columns |
Use value_counts for a quick frequency table. Use groupby when you also need sums, means, or distinct counts for the same groups.
Exercise
A DataFrame orders has columns country, channel and amount. Some country values are missing. Write one expression that returns, for each (country, channel) pair, the percentage of all 100-percent-of-rows orders it represents, including the rows with a missing country, with the largest percentage first.
Show answer
Use orders.value_counts(["country", "channel"], normalize=True, dropna=False) * 100. Setting dropna=False keeps rows with a missing country in both the result and the denominator, so the percentages add up to 100. The default sort already puts the largest first.
Exercise
df.value_counts(["city", "plan"]) returns counts that add up to 6 for a 7-row DataFrame. Why, and how do you make the counts add up to 7?
Show answer
Row 6 has a missing city, and with the default dropna=True a row is excluded when any selected column is missing. Pass dropna=False so the tuple (NaN, "free") is counted too, which makes the total 7.