Sub topic 2
Common Rename Pitfalls
Assume you can create a pandas DataFrame, select columns by label, and use Python dictionaries and string methods. This chapter focuses on checking column renames and removing duplicate rows safely.
Common rename pitfalls
rename() returns a new DataFrame by default. It does not change the original unless you assign the result:
import pandas as pd
df = pd.DataFrame({"Order ID": [1, 2], "Total $": [10, 20]})
df = df.rename(columns={
"Order ID": "order_id",
"Total $": "total",
})
print(df.columns.tolist())
# ['order_id', 'total']A mapping key that does not match a column is ignored by default. Use errors="raise" when a missing label indicates a bug. Avoid relying on inplace=True; assignment makes the transformation explicit and easier to chain.
What counts as a duplicate row
A duplicate row has the same values in the compared columns as an earlier row. The index is not part of this comparison. If you compare only selected columns, rows with different values elsewhere can still be duplicates for that subset.
Before deduplicating, normalize values when needed. For example, "Ann" and " ann " are different strings until you strip whitespace and standardize case.
Finding duplicates with `duplicated()`
duplicated() returns a Boolean Series. The first occurrence is False; later matching rows are True. Count duplicates with .sum().
df = pd.DataFrame({
"order_id": [1, 2, 2, 3],
"customer": ["Ann", "Bob", "Bob", "Cy"],
"total": [10.0, 20.0, 20.0, 5.0],
})
is_duplicate = df.duplicated()
print(is_duplicate.tolist()) # [False, False, True, False]
print(is_duplicate.sum()) # 1Dropping duplicates with `drop_duplicates()`
drop_duplicates() keeps the first occurrence by default. Use subset to define the identifying columns and keep="last" to retain the last occurrence. To keep the latest record, sort by its date first.
The original index remains unless you pass ignore_index=True.
latest = (
df.sort_values("order_id")
.drop_duplicates(subset="order_id", keep="last", ignore_index=True)
)
print(latest["order_id"].tolist()) # [1, 2, 3]Exercise
What does df.drop_duplicates(subset="user", keep="last") retain?
Show answer
It retains the last row for each distinct user value and removes earlier rows with the same user.