Counting Groups

How many of each, and the difference between size and count.

value_counts for one column

The quickest answer to "how many of each" and sorted by frequency by default.

import pandas as pd

s = pd.Series(["maths", "art", "maths"])
print(s.value_counts().to_dict())

size counts rows, count counts values

On a group, size includes rows whose value is missing and count does not. Which you want depends on whether a gap is still a row.

import pandas as pd

df = pd.DataFrame({"k": ["a", "a"], "v": [1, None]})
print(df.groupby("k")["v"].size().to_dict())
print(df.groupby("k")["v"].count().to_dict())

Exercise

Try It Yourself

Write counts_by(df, column) returning a dictionary of each distinct value in that column to how many rows have it.

Press Run to see output

Check Your Understanding