Sub topic 10
When to use concat instead of merge
This chapter assumes you can already run merge on a key column and read its output. It also assumes you know what a DataFrame index is. Here you will learn when pd.concat is the better tool, how it aligns data, and which mistakes it produces.
The core difference
merge looks for matching key values and builds new rows from the matches. The number of output rows depends on how many keys match, and on how often each key repeats.
concat does not match values. It places DataFrames next to each other or on top of each other. It aligns them only on labels: the column labels when stacking rows, and the index labels when placing frames side by side. Rows are never multiplied, and no match is ever searched for.
| Question | Use |
|---|---|
| Do the tables describe different things that share a key, such as customers and orders? | `merge` or `join` |
| Do the tables hold the same kind of records, such as one file per month? | `concat` |
| Are the pieces already aligned by index label, and do you want them side by side? | `concat(axis=1)` or `join` |
| Must the rows be matched by value, with possible duplicates? | `merge` |
Stacking rows with axis=0
The default is axis=0, which stacks frames vertically. Columns are matched by name.
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 result has four rows. The keys argument adds an outer level to the index, so each row records which frame it came from. You can pull a piece back out with stacked.loc["feb"].
Merging these two frames would answer a different question. It would put the months side by side:
wide = jan.merge(feb, on="id", suffixes=("_jan", "_feb"))
print(wide)The output has two rows with the columns id, sales_jan, and sales_feb. Use merge to compare the months per id. Use concat to get one long table with a row per month and id. Reaching for merge to stack data is a common mistake. It creates _x and _y columns and silently drops ids that exist in only one frame, when the default inner join is used.
Keeping the source as a column
keys produces a MultiIndex. Often you want a normal column instead. Build the label before you concatenate:
frames = [df.assign(month=name) for name, df in {"jan": jan, "feb": feb}.items()]
combined = pd.concat(frames, ignore_index=True)
print(combined)ignore_index=True discards the old index labels and numbers the rows 0 to 3. Without it, the result would repeat the labels 0 and 1. If you pass keys together with ignore_index=True, the keys are discarded, so pick one approach.
Duplicate index labels
When you stack frames without ignore_index, each frame keeps its own index. Two frames that both start at 0 produce a result with two rows labelled 0. Later, .loc[0] returns both rows, and an assignment by label can change more rows than you meant. Ask pandas to refuse overlapping labels with verify_integrity=True:
try:
pd.concat([jan, feb], verify_integrity=True)
except ValueError as err:
print("Overlapping index:", err)Use this check only when the index labels are meaningful, such as order numbers or dates. If the index is just a default row counter, ignore_index=True is the right fix.
Columns that do not match
concat takes the union of the column names by default. A frame that lacks a column gets NaN in that column.
mar = pd.DataFrame({"id": [1, 3], "sales": [120, 90], "region": ["N", "S"]})
print(pd.concat([jan, mar], ignore_index=True))
print(pd.concat([jan, mar], ignore_index=True, join="inner"))The first call keeps region, with NaN for the January rows. The second call, with join="inner", keeps only the columns that every frame has, which are id and sales. The name join here refers to the set of labels on the other axis. It has nothing to do with the key matching you learned for merge.
Watch the dtypes. An integer column that gets NaN values becomes float64. A column that is a string in one frame and a number in another becomes object. After a concat, check combined.dtypes before you use the result in a later merge, because a key with a changed dtype causes the mismatches described in the earlier chapter on key problems.
Misspelled column names are another source of surprises. If one file calls the column Sales and another calls it sales, concat treats them as two different columns and fills each with NaN where it is missing. Compare df.columns across the pieces, or normalise the names with df.columns = df.columns.str.lower() before you stack them.
Placing frames side by side with axis=1
With axis=1, concat lines frames up by index label and joins their columns:
names = pd.DataFrame({"name": ["Ana", "Ben", "Chen"]}, index=[1, 2, 3])
totals = pd.DataFrame({"total": [65.0, 15.5]}, index=[1, 3])
print(pd.concat([names, totals], axis=1))The result has three rows. Ben, with index 2, has NaN in total because totals has no row 2. The default is an outer join on the index, so no row from either frame is lost. Pass join="inner" to keep only labels present in every frame.
This is close to names.join(totals). The differences are:
joinis a left join by default andconcat(axis=1)is an outer join by default.concataccepts a list of any length, which suits combining many pieces in one call.joincan match a column of the left frame against the index of the right frame withon=.concatcannot.
The duplicate-label failure
concat(axis=1) needs the index labels in each frame to be unique, because it has to decide which row lines up with which. If an index has repeated labels, and the indexes are not identical, pandas raises pandas.errors.InvalidIndexError, with a message about reindexing only being valid with uniquely valued indexes. merge does not have this restriction. It would produce every combination of the repeated keys, which is the many-to-many behaviour from the cardinality chapter.
This is also why concat(axis=1) is risky when the frames merely have the same length. If two frames have the same number of rows but different index labels, the rows are not paired by position. They are paired by label, and you get NaN in both directions. To pair by position, reset both indexes first with reset_index(drop=True).
Build the list first, then concatenate once
Each call to concat copies all the data it combines. Calling it inside a loop copies the growing result again on each pass, and the cost grows quickly with the number of pieces. Collect the frames in a list and make a single call:
pieces = []
for month, sales in [("jan", [100, 200]), ("feb", [110, 190]), ("mar", [120, 210])]:
pieces.append(pd.DataFrame({"id": [1, 2], "sales": sales, "month": month}))
report = pd.concat(pieces, ignore_index=True)
print(report.shape)The shape is (6, 3). The same pattern applies when you read many files, with one pd.read_csv call per file in the list.
A related gotcha concerns empty frames. Concatenating a list that includes empty or all-NaN frames can change the dtype of the result, and recent pandas versions warn about it. Filter out empty pieces first, for example with [p for p in pieces if not p.empty].
Using concat and merge together
A typical pipeline uses both. First stack the pieces that have the same structure. Then merge the stacked table with reference data once.
customers = pd.DataFrame({"id": [1, 2], "name": ["Ana", "Ben"]})
enriched = report.merge(customers, on="id", how="left", validate="many_to_one")
print(enriched.shape)This does the merge once, on the complete table, instead of repeating it for each month. The validate="many_to_one" check confirms that customers has one row per id, so the merge cannot multiply rows. The result has 6 rows.
Summary of what to check
- Choose by the question you are asking, not by what happens to run. Stacking records means
concat. Matching records by value meansmerge. - After a row-wise concat, look at the index, the column list, and the dtypes.
- After a column-wise concat, compare the index labels first.
- Collect the pieces in a list and call
concatonce.
Exercise
You have twelve DataFrames, one per month. Each has the columns order_id, customer_id, and amount, and each has a default index starting at 0. You want one table with a month column and no repeated index labels. Which function do you use, and how do you build the table without calling it in a loop?
Show answer
Use pd.concat, because the frames hold the same kind of record, so no key matching is needed. Build a list with [df.assign(month=name) for name, df in monthly.items()], where monthly is a dict of month name to DataFrame. Then call pd.concat(frames, ignore_index=True) once. assign adds the month column, and ignore_index=True replaces the repeated 0-based labels with 0 to N-1.
Exercise
a has index [1, 2, 3] and b has index [2, 3, 4]. What does pd.concat([a, b], axis=1) return, and how would you keep only the labels that appear in both?
Show answer
It returns four rows, labelled 1, 2, 3, and 4, because the default is an outer join on the index. Row 1 has NaN in the columns from b, and row 4 has NaN in the columns from a. To keep only labels 2 and 3, pass join="inner".