Sub topic 13
Performance and Memory Tips
This chapter assumes you can run merge and join, know the join types, and understand how duplicate keys change row counts. Here you will learn which choices make merges slower or larger, and how to reduce that cost.
Where the cost comes from
A merge builds a hash table from the keys of one table and looks up the keys of the other. Time and memory grow with three things: the number of rows, the number of columns carried through, and the number of output rows. The output size is the factor people most often miss. A many-to-many merge can return far more rows than either input has.
Shrink the inputs first
Select only the columns you need before merging. Filter rows you will discard anyway. Both steps cut the data pandas must copy into the result.
import pandas as pd
customers = pd.DataFrame({
"customer_id": [1, 2, 3],
"name": ["Ana", "Ben", "Chen"],
"notes": ["vip", "", "late payer"],
})
orders = pd.DataFrame({
"order_id": [10, 11, 12, 13],
"customer_id": [1, 1, 3, 4],
"amount": [25.0, 40.0, 15.5, 60.0],
})
slim = customers[["customer_id", "name"]].merge(
orders[orders["amount"] > 20],
on="customer_id",
)
print(slim)The notes column and the small order never enter the merge.
Use compact key dtypes
Keys stored as Python strings (object dtype) are slower to hash and larger in memory than numbers. Two fixes help:
- Use the smallest integer type that fits, such as
int32instead ofint64. - Use the
categorydtype for string keys that repeat a lot.
orders["customer_id"] = orders["customer_id"].astype("int32")
customers["customer_id"] = customers["customer_id"].astype("int32")
print(orders.memory_usage(deep=True))Both sides must have the same dtype. Mixed integer sizes still merge, but matching types avoid conversion work.
cat = pd.CategoricalDtype(["A", "B", "C"])
left = pd.DataFrame({"code": pd.Series(["A", "B"], dtype=cat), "x": [1, 2]})
right = pd.DataFrame({"code": pd.Series(["B", "C"], dtype=cat), "y": [3, 4]})
print(left.merge(right, on="code", how="outer"))Categorical keys merge efficiently when both columns share the same categories. If the categories differ, pandas falls back to object and you lose the benefit.
Estimate the output before you merge
Count duplicates on each side to predict the row count. For an inner join, the output size is the sum, over shared keys, of the left count times the right count.
left_counts = customers["customer_id"].value_counts()
right_counts = orders["customer_id"].value_counts()
expected = (left_counts * right_counts).sum()
print("Inner join rows:", expected)left_counts * right_counts aligns on the index, so keys missing from one side become NaN and drop out of the sum. If expected is far larger than your inputs, you probably have duplicate keys on both sides. Fix that before running the merge.
Prefer index joins when the index is the key
An index lookup avoids building a temporary hash table from a column. If you join to the same lookup table many times, set its index once and reuse it.
prices = pd.DataFrame(
{"price": [1.5, 12.0]},
index=pd.Index([1, 2], name="sku"),
)
items = pd.DataFrame({"sku": [1, 2, 2], "qty": [3, 1, 2]})
print(items.join(prices, on="sku"))Sorting the index first can speed up repeated lookups on large tables, but measure before assuming a gain.
Other habits that help
- Merge once with several keys instead of chaining merges that repeat work.
- Drop helper columns such as
_mergeafter auditing, sinceindicator=Trueadds a column. - Delete intermediate DataFrames you no longer need, so memory is freed.
- Measure with
%timeitortime.perf_counter()on a sample before optimizing the full data.
Exercise
A left table has 1,000 rows and a right table has 500 rows. The key value "X" appears 100 times in the left table and 50 times in the right table. How many rows does an inner merge produce for "X" alone, and why does it matter?
Show answer
100 × 50 = 5,000 rows. Each left row pairs with each right row that has the same key, so a many-to-many merge on one key value already produces more rows than both inputs combined. Estimate this with value_counts before merging to avoid unexpected memory use.