Sub topic 11
Counting combinations of columns
This chapter assumes you know how to select columns from a DataFrame and have used Series.value_counts. Here you count how often a combination of values occurs across several columns.
Counting pairs with DataFrame.value_counts
DataFrame.value_counts works like the Series version, but it treats each row as a tuple of values. Pass a list of column names to choose which columns form the combination.
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 of (city, plan). The counts are:
(Oslo, free): 2(Rome, pro): 2(Oslo, pro): 1(Paris, pro): 1
The result is sorted from most to least frequent. Pairs with equal counts have no order you should rely on.
Without an argument, df.value_counts() uses every column. That counts how many times each complete row occurs, so it is a quick way to see which rows are duplicated.
Missing values in combinations
The last row has a missing city. By default value_counts drops any row where one of the chosen columns is missing, so that row is absent above and the counts add up to 6, not 7. Pass dropna=False to keep it.
with_missing = df.value_counts(["city", "plan"], dropna=False)
print(with_missing) # adds one row: (NaN, free) with a count of 1Proportions and a flat table
normalize=True and sort=False work as they do for a Series. The fractions are relative to the rows that were counted.
shares = df.value_counts(["city", "plan"], normalize=True)
print(shares.sum()) # 1.0The MultiIndex is awkward to filter or merge. Call reset_index to turn it into an ordinary DataFrame with one column per key.
flat = pair_counts.reset_index(name="n")
print(flat)
# city plan n
# 0 Oslo free 2
# 1 Rome pro 2
# 2 Oslo pro 1
# 3 Paris pro 1Laying the counts out as a table
When you have two columns, you can move one index level into the columns with unstack. pd.crosstab gives the same table in one call.
table = pair_counts.unstack(fill_value=0)
same_table = pd.crosstab(df["city"], df["plan"])
print(same_table)
# plan free pro
# city
# Oslo 2 1
# Paris 0 1
# Rome 0 2crosstab also excludes rows with missing values by default. Use value_counts when you want a long list of pairs, and the table form when you want to compare the two columns side by side.
Exercise
Using the DataFrame above, how many rows does df.value_counts(["city", "plan"], dropna=False) return, and what is the sum of its counts?
Show answer
It returns 5 rows, the four pairs listed earlier plus (NaN, free). The counts sum to 7, the number of rows in df, because no row is dropped.