Sub topic 1
What you are counting: Series and DataFrame columns
Prerequisites
You should know basic Python syntax, how to create a pandas Series and DataFrame, and how to select a DataFrame column.
Series and DataFrame columns
A DataFrame is a table with rows and named columns. A selected column is a Series, which is a one-dimensional sequence of values with an index. Counting operations usually run on a Series.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
cities = df["city"] # a Series
city_counts = cities.value_counts()
print(city_counts)The same DataFrame can support different questions:
| Question | pandas operation |
|---|---|
| How many rows have each city? | `df["city"].value_counts()` |
| How many city entries are present? | `df["city"].count()` |
| How many different cities exist? | `df["city"].nunique()` |
How missing values affect counts
A missing value means that data was not supplied. In pandas, a missing text value often appears as None, and pandas represents it as a missing value internally.
Many counting methods exclude missing values by default. This prevents an unknown value from being treated as an ordinary category. You can include missing values when that is analytically useful.
This diagram shows the distinction:
Counting non-null values with count
Series.count() returns the number of non-missing entries. For the city column, it returns 6, because one of the seven rows is missing a city.
count() counts entries, not distinct values and not row combinations.
Counting occurrences with value_counts
Series.value_counts() returns a Series whose index contains each observed value and whose values contain its frequency. It sorts frequencies from largest to smallest by default. Missing values are excluded unless you pass dropna=False.
Turning counts into proportions
Pass normalize=True to return proportions instead of raw counts. By default, pandas divides by the number of non-missing values. Use dropna=False when the missing category should be part of the denominator.
print(df["city"].value_counts(normalize=True))
print(df["city"].value_counts(dropna=False, normalize=True))The first result describes the distribution among known cities. The second describes all rows, including the missing city.
Exercise
Which expression counts every row's city value, including the missing value?
Show answer
df["city"].value_counts(dropna=False)