Sub topic 3
Removing Duplicate Rows and Counting Combinations in pandas
Assume you know basic Python, can create a pandas DataFrame, and can select columns. These operations help you summarize repeated records.
Removing duplicate rows with `drop_duplicates`
drop_duplicates returns a DataFrame with repeated rows removed. Use subset to define which columns identify a duplicate. The default keeps the first matching row.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Rome", "Oslo", "Paris", "Rome", "Oslo", None],
"plan": ["free", "pro", "free", "pro", "pro", "pro", "free"],
})
deduped = df.drop_duplicates(subset=["city", "plan"], keep="first")
print(deduped)Use keep="last" to keep the final row, or keep=False to remove every row in a duplicated group. The method returns a new DataFrame unless you explicitly use inplace=True.
Counting combinations of columns
DataFrame.value_counts counts distinct combinations:
pair_counts = df.value_counts(["city", "plan"])
print(pair_counts)The result is a Series indexed by the column combination. Missing combinations are omitted by default.
Counting within groups: `size` versus `count`
After groupby, size() counts rows, including missing values. count() counts non-missing values in the selected column.
rows_per_plan = df.groupby("plan").size()
cities_per_plan = df.groupby("plan")["city"].count()Distinct counts per group
Use nunique() to count different non-missing values in each group:
distinct_cities = df.groupby("plan")["city"].nunique()Add dropna=False when a missing value should count as one distinct item.
Cross-tabulating two columns
pd.crosstab displays pair counts as a table:
table = pd.crosstab(df["city"], df["plan"])
print(table)Counting numeric data in bins
For numeric values, pd.cut creates intervals before counting:
ages = pd.Series([18, 22, 35, 41, 67])
age_bins = pd.cut(ages, bins=[0, 18, 35, 65, 100])
print(age_bins.value_counts().sort_index())Counting categorical columns
A categorical column stores values from a defined set of labels. value_counts counts observed labels. Unused categories require observed=False in grouped operations.
Exercise
Which method counts all rows in each group, even when a selected column contains missing values?
Show answer
groupby(...).size().