Sub topic 10
When to Use concat Instead of merge
This chapter assumes you can create DataFrames, understand the index, and have used merge with a key column. You will learn when pd.concat is the right tool and when it is not.
Two different jobs
merge matches rows by key values. It adds columns from one table to rows of another.
concat does not match anything. It places DataFrames next to each other or on top of each other and aligns them by index labels or column names.
| Task | Tool |
|---|---|
| Add columns from a lookup table using a shared key | `merge` or `join` |
| Stack tables that have the same columns (for example, one file per month) | `concat` |
| Put tables side by side when row labels already line up | `concat` with `axis=1` |
A quick test: if you would describe the task as "look up", use merge. If you would describe it as "append" or "stack", use concat.
Stacking rows
Suppose two months of sales have identical columns. Passing them to concat as a list stacks them.
import pandas as pd
jan = pd.DataFrame({"id": [1, 2], "sales": [100, 200]})
feb = pd.DataFrame({"id": [1, 2], "sales": [110, 190]})
stacked = pd.concat([jan, feb], keys=["jan", "feb"])
print(stacked)The keys argument adds an outer index level that records which source each row came from. The output has a two-level index: jan and feb, each with the labels 0 and 1.
Notice that id 1 appears twice. concat does not treat the id column as a key, so it never combines or removes those rows. A merge on id would have produced one row per matching pair instead.
Common behaviors and errors
- Duplicate index labels. Without
keys, stacking two default-indexed frames gives labels 0, 1, 0, 1. Passignore_index=Truefor a fresh 0 to n-1 index, orkeysto keep the origin. - Mismatched columns. By default,
join="outer"keeps the union of columns and fills gaps withNaN. Usejoin="inner"to keep only the shared columns. A misspelled column name silently creates a new column, so checkstacked.columnsafter combining. - dtype changes. If a column is integer in one frame and has
NaNin the other, the result becomes float. An object column mixed with numbers becomes object. - Wrong axis.
axis=1aligns on the index, not on a key column. If the two frames have different row order or labels, you get misaligned rows or rows full ofNaN. - Appending in a loop. Calling
concatonce per iteration copies the data each time. Collect the pieces in a list and callconcatonce.
import pandas as pd
pieces = []
for month in ["jan", "feb", "mar"]:
pieces.append(pd.DataFrame({"month": [month], "sales": [100]}))
all_months = pd.concat(pieces, ignore_index=True)
print(all_months)Using both together
A common pipeline stacks many files with concat, then enriches the result with one merge. Doing the stack first means the lookup runs once on the combined table.
import pandas as pd
jan = pd.DataFrame({"id": [1, 2], "sales": [100, 200]})
feb = pd.DataFrame({"id": [1, 2], "sales": [110, 190]})
names = pd.DataFrame({"id": [1, 2], "name": ["Ana", "Ben"]})
report = pd.concat([jan, feb], ignore_index=True).merge(names, on="id")
print(report)The result has four rows, each with a name attached.
Exercise
You have east and west DataFrames with identical columns, and you want one DataFrame with a clean 0, 1, 2, ... index. A colleague proposes east.merge(west). What should you use instead, and why?
Show answer
Use pd.concat([east, west], ignore_index=True). The task is stacking rows, not matching on a key. merge with no key would join on all shared columns and keep only identical rows, which drops data.
Exercise
You run pd.concat([a, b], axis=1) and the result has many NaN values. a has index 0 to 4 and b has index 10 to 14. What happened, and how would you fix it if the rows should pair by position?
Show answer
axis=1 aligns on index labels, and the two indexes share no labels, so each frame fills the other's rows with NaN. Call reset_index(drop=True) on both frames before concatenating, or use merge if the rows should match on a key column.