Sub topic 4
Counting Occurrences with value_counts
This chapter assumes you can build a pandas DataFrame and select a column from it. You should also know that a column is a Series, and that missing values appear as None or NaN.
What value_counts returns
Series.value_counts() counts how many times each distinct value appears in a Series. The result is a new Series. Its index holds the distinct values and its values hold the counts. The rows are sorted from the most frequent value to the least frequent.
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()
print(counts)The output lists Oslo with 3, Rome with 2 and Paris with 1. The row with the missing city does not appear in the output.
Missing values are dropped by default
By default, value_counts leaves out missing values. The counts above add up to 6, even though the column has 7 rows. Pass dropna=False to keep the missing value as its own entry.
with_missing = df["city"].value_counts(dropna=False)
print(with_missing)The result now has a fourth entry for the missing value, with a count of 1. Use this form when you need to see how much data is absent.
Counts as proportions
Pass normalize=True to get fractions instead of counts. Each fraction is the count divided by the total number of counted values.
shares = df["city"].value_counts(normalize=True)
print(shares)Oslo is 3 of 6 values, so its share is 0.5. The denominator is 6, not 7, because the missing value was dropped. If you combine normalize=True with dropna=False, the denominator becomes 7 and the shares change. Decide which total you mean before you report a percentage.
Reading the result
Because the result is a Series, you can index it like one. The distinct values are the index, so you can look up a count by label or by position.
print(counts["Oslo"]) # 3
print(counts.iloc[0]) # 3, the most frequent value
print(counts.index.tolist()) # ['Oslo', 'Rome', 'Paris']Common errors
- Calling it on the whole DataFrame by mistake.
df.value_counts()counts whole-row combinations, not one column. Select the column first, as indf["city"].value_counts(). - Forgetting about missing values. The total of the counts can be smaller than
len(df). Comparecounts.sum()withlen(df)to check. - Expecting a fixed order for ties. When two values have the same count, do not rely on their relative order. Sort the result explicitly if the order matters for your output.
How the pieces fit
Exercise
A column has 10 rows, and 2 of them are missing. You call value_counts(normalize=True) and the value "A" appears in 4 rows. What share does "A" get, and what would it be with dropna=False?
Show answer
With the default dropna=True, the denominator is the 8 non-missing values, so "A" gets 4/8 = 0.5. With dropna=False, the denominator is all 10 rows, so "A" gets 4/10 = 0.4, and the missing value gets 2/10 = 0.2.