Sub topic 13
Performance and memory tips
This chapter covers how to keep merges fast and small. It assumes you can already run merge, join, and concat, that you know how join types and cardinality change row counts, and that you know the common dtypes (int64, object, category). Timings differ by machine and pandas version, so the code prints measurements instead of promising numbers.
Where the cost comes from
A merge costs about the size of the inputs plus the size of the output. pandas builds a lookup structure from the keys of one table, probes it with the keys of the other, and then copies the matching rows into a new DataFrame. Three things drive the cost:
- Row counts of both inputs.
- Columns carried along. Every column in the result is copied, including columns you never use afterwards.
- Output size. Duplicate keys multiply rows, and a merge that produces ten times more rows than you expected is slow and memory-hungry.
Most speedups come from shrinking these three before the merge runs. Tuning the merge call itself usually helps much less.
Estimate the output size first
For an inner join, the number of output rows is the sum, over each key value, of the left count times the right count. You can compute that from value_counts without running the merge.
import pandas as pd
left = pd.DataFrame({"key": [1, 1, 2, 3], "a": range(4)})
right = pd.DataFrame({"key": [1, 1, 1, 2, 4], "b": range(5)})
left_counts = left["key"].value_counts()
right_counts = right["key"].value_counts()
expected = int(left_counts.mul(right_counts, fill_value=0).sum())
actual = len(left.merge(right, on="key"))
print(expected, actual)Both numbers are 7. Key 1 gives 2 × 3 = 6 rows, key 2 gives 1 × 1 = 1 row, and keys 3 and 4 appear on only one side, so they contribute nothing. For a left join, add the left rows whose keys have no match on the right.
This check is cheap, and it catches many-to-many explosions before they use all your memory. Two tables of 1 million rows each that share one key value would produce 10^12 rows.
Trim rows and columns before merging
The result carries every column of both inputs unless you remove them. Select the columns you need and filter the rows you can discard before you call merge.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 200_000
orders = pd.DataFrame({
"order_id": np.arange(n),
"customer_id": rng.integers(0, 1_000, n),
"amount": rng.random(n),
"note": rng.choice(["rush", "gift", "none"], n),
})
customers = pd.DataFrame({
"customer_id": np.arange(1_000),
"region": rng.choice(["north", "south", "east", "west"], 1_000),
"segment": rng.choice(["retail", "wholesale"], 1_000),
})
def mb(df):
return df.memory_usage(deep=True).sum() / 1e6
everything = orders.merge(customers, on="customer_id")
needed = orders[["order_id", "customer_id", "amount"]].merge(
customers[["customer_id", "region"]], on="customer_id"
)
print(f"all columns: {mb(everything):.1f} MB")
print(f"needed columns: {mb(needed):.1f} MB")memory_usage(deep=True) matters here. Without deep=True, pandas counts only the pointer for each object (text) value and ignores the strings themselves, which understates the size of text columns.
Filtering rows works the same way. If you only need 2026 orders, filter orders first and merge the smaller table. Filtering after the merge gives the same answer but does the full work first.
If the right table has duplicate keys you do not need, remove them first:
latest = (
orders.sort_values("order_id")
.drop_duplicates("customer_id", keep="last")
[["customer_id", "amount"]]
)Use validate="one_to_one" or "many_to_one" afterwards to confirm the key really is unique.
Match key dtypes and shrink the rest
Keys should have identical dtypes
If one key is int64 and the other is object, pandas raises an error or, in older cases, compares values slowly. Mixed numeric widths such as int32 and int64 work, but pandas has to convert one side. Pick one dtype for the key on both sides before merging, and convert once rather than in every merge.
Repeated text becomes category
A column with few distinct values and many rows, such as region above, stores each string once as a category and keeps small integer codes per row.
customers["region"] = customers["region"].astype("category")
customers["segment"] = customers["segment"].astype("category")
needed_cat = orders[["order_id", "customer_id", "amount"]].merge(
customers[["customer_id", "region"]], on="customer_id"
)
print(needed_cat["region"].dtype)
print(f"with category: {mb(needed_cat):.1f} MB")The region column stays categorical after the merge, so the result is smaller than the object version.
Numeric columns can be smaller
Floats default to float64 and integers to int64. If the values fit, pd.to_numeric(col, downcast="integer") or downcast="float" picks a smaller type. Do this to non-key columns, or do it identically to both key columns. Downcasting floats loses precision, so avoid it for money or any column where exact sums matter.
Choose merge or join by measurement
DataFrame.join with on= and merge with left_index=True or right_index=True do similar work. The index-based forms can be faster when an index is already built and unique, because the lookup structure may already exist. The gain depends on your data, so time both on a realistic sample.
import time
prices = customers.set_index("customer_id")[["segment"]]
small_orders = orders[["order_id", "customer_id"]]
start = time.perf_counter()
by_merge = small_orders.merge(
customers[["customer_id", "segment"]], on="customer_id", how="left"
)
t_merge = time.perf_counter() - start
start = time.perf_counter()
by_join = small_orders.join(prices, on="customer_id")
t_join = time.perf_counter() - start
print(f"merge: {t_merge:.4f}s join: {t_join:.4f}s")
print(by_merge["segment"].equals(by_join["segment"]))The last line should print True, which confirms the two approaches return the same values. Run the timing a few times, because the first run includes one-off costs such as building lookup tables. For serious comparisons, use %timeit in Jupyter or the timeit module.
Some smaller settings are worth knowing:
sort=Falseis the default formerge, so the result order follows the join type. Avoidsort=Trueunless you need sorted keys, because sorting the result costs extra.how="outer"must combine both key sets and is the most expensive join type. Useinnerorleftwhen the question allows it.indicator=Trueadds a column. That is cheap for an audit on a sample, but you can leave it out of the final production run.
Many tables: avoid a chain of wide merges
A loop that merges one table at a time into a growing result copies the whole result on every pass. When several tables share a unique key, put the key in the index and use one concat along the columns.
ids = np.arange(1_000)
frames = [
pd.DataFrame({"id": ids, f"metric_{i}": rng.random(len(ids))}).set_index("id")
for i in range(5)
]
wide = pd.concat(frames, axis=1)
print(wide.shape)concat with axis=1 aligns on the index and keeps the union of the index values, like an outer join. It only behaves cleanly when each index is unique. If an index has duplicates, concat raises an error (or aligns incorrectly), and you should use merge instead.
Edge cases and failure modes
- Many-to-many explosion. The output is the product of the duplicate counts. Estimate it first, then aggregate one side (
groupby(...).agg(...)) so the key is unique. - Missing keys.
NaNkeys match each other in a merge. If many rows have missing keys, they can create a large block of matches. Drop or fill them before merging. - Integers turned into floats. A left or outer join with unmatched rows puts
NaNinto the columns from the other table, and anint64column becomesfloat64. If you need integers, use a nullable dtype such asInt64before the merge. - Copies persist. The inputs stay in memory next to the result. Delete intermediate tables with
delonce you are done, or reassign the name, so the memory can be reclaimed. - Data larger than memory. If the inputs do not fit in RAM, loading them in chunks, filtering each chunk, and merging the reduced pieces may work. At larger scale, a database or a tool built for out-of-core work is a better fit than tuning pandas.
Summary checklist
- Estimate the output rows with
value_countsbefore a risky merge. - Remove unneeded rows, columns, and duplicate keys first.
- Give both keys the same dtype.
- Turn repeated text into
categoryand shrink numeric columns, except keys with mismatched categories. - Time
mergeagainstjoinon a sample. - Replace chains of merges with one
concat(axis=1)when the indexes are unique. - Confirm the result with
validateand compare row counts.
Exercise
A table events has 2 million rows and a user_id column. A table users has 500 000 rows, 20 columns, and a unique user_id. You only need user_id and country from users, and country has about 200 distinct values. Describe how you would merge them to minimize memory, and which validate value you would pass.
Show answer
Select only user_id and country from users before merging, make sure user_id has the same dtype in both tables, and convert country to category. Then run events.merge(users_small, on="user_id", how="left", validate="many_to_one"). This keeps the left table's 2 million rows, copies a single small categorical column, and raises an error if user_id is not unique in users.
Exercise
left has key counts {A: 4, B: 2} and right has key counts {A: 3, B: 5, C: 1}. How many rows does an inner merge on the key return, and how many does a left merge return?
Show answer
The inner merge returns 4 × 3 + 2 × 5 = 22 rows, because key C appears only on the right. The left merge also returns 22 rows, because every left key (A and B) has matches on the right, so no unmatched left rows are added.