Sub topic 15
Combining tables with concat and merge
Real analyses rarely start with one clean table. You usually have several tables to join into one. This chapter covers the two main tools, pd.concat and DataFrame.merge, and the mistakes that most often go wrong with them.
This chapter assumes you know how a DataFrame stores columns that share an Index, how label alignment works in arithmetic, and how NaN marks missing values. It does not assume you have used joins before.
Two different questions
The two functions answer different questions.
concatstacks tables. It places them end to end (more rows) or side by side (more columns) and lines them up by index labels or column names.mergematches rows. It pairs rows from two tables whose values in one or more key columns are equal, like a database join.
Use concat when the tables describe the same kind of thing, such as monthly files with the same columns. Use merge when the tables describe different things that are linked by a shared key, such as cities and region labels.
Stacking rows with concat
pd.concat takes a list of objects. By default it stacks them vertically (axis=0) and keeps each table's original index labels.
import pandas as pd
jan = pd.DataFrame({"city": ["Oslo", "Lima"], "sales": [5, 8]})
feb = pd.DataFrame({"city": ["Oslo", "Pune"], "sales": [6, 4]})
both = pd.concat([jan, feb])
print(both)The result has index labels 0, 1, 0, 1. Duplicate labels are legal, but they make loc return several rows for one label. Two fixes are common:
import pandas as pd
jan = pd.DataFrame({"city": ["Oslo", "Lima"], "sales": [5, 8]})
feb = pd.DataFrame({"city": ["Oslo", "Pune"], "sales": [6, 4]})
# Option 1: renumber the rows 0..n-1
both = pd.concat([jan, feb], ignore_index=True)
print(both)
# Option 2: keep the origin of each row with an outer index level
tagged = pd.concat([jan, feb], keys=["jan", "feb"])
print(tagged.loc["feb"])Use ignore_index=True when the old labels carry no meaning. Use keys when you want to remember which input each row came from.
Mismatched columns
If the tables have different columns, concat keeps the union of all columns and fills the gaps with NaN.
import pandas as pd
a = pd.DataFrame({"city": ["Oslo"], "sales": [5]})
b = pd.DataFrame({"city": ["Lima"], "returns": [1]})
print(pd.concat([a, b], ignore_index=True))The output has the columns city, sales, and returns. Each row has NaN in the column its source table lacked. Passing join="inner" keeps only the columns present in every table. A misspelled column name therefore shows up as a surprise column full of NaN rather than as an error. Check both.columns after combining.
Placing columns side by side
With axis=1, concat aligns on the index, the same alignment you saw in arithmetic.
import pandas as pd
pop = pd.Series([0.7, 10.7], index=["Oslo", "Lima"], name="pop_m")
area = pd.Series([454, 2672, 100], index=["Lima", "Oslo", "Rome"], name="area_km2")
print(pd.concat([pop, area], axis=1))The default is an outer join on the index, so Rome appears with NaN for pop_m. Pass join="inner" to keep only labels present in both. Series names become the column names, so name your Series first.
Matching rows with merge
merge joins two DataFrames on key columns. It returns a new DataFrame, and by default the index of the result is a fresh 0..n-1 range, not the inputs' indexes.
import pandas as pd
cities = pd.DataFrame({"city": ["Oslo", "Lima", "Pune"], "region": ["EU", "SA", "AS"]})
labels = pd.DataFrame({"region": ["EU", "AS"], "label": ["Europe", "Asia"]})
print(cities.merge(labels, on="region", how="left"))The `how` argument
The how argument decides what happens to rows without a match.
| how | Rows kept |
|---|---|
| `inner` (default) | Only keys present in both tables |
| `left` | All rows of the left table, with NaN for unmatched right columns |
| `right` | All rows of the right table, with NaN for unmatched left columns |
| `outer` | All rows from both tables |
| `cross` | Every pairing of left and right rows, with no key |
The default is inner, which silently drops unmatched rows. If you expected to keep every row of your main table, write how="left" explicitly.
Keys with different names
When the key columns are named differently, use left_on and right_on. Both columns appear in the result, so drop one if you do not need it.
import pandas as pd
cities = pd.DataFrame({"city": ["Oslo", "Lima"], "code": ["EU", "SA"]})
labels = pd.DataFrame({"region": ["EU", "SA"], "label": ["Europe", "South America"]})
out = cities.merge(labels, left_on="code", right_on="region").drop(columns="region")
print(out)Overlapping column names
If both tables have a non-key column with the same name, pandas appends _x and _y. Choose clearer names with suffixes:
import pandas as pd
a = pd.DataFrame({"id": [1, 2], "score": [10, 20]})
b = pd.DataFrame({"id": [1, 2], "score": [11, 21]})
print(a.merge(b, on="id", suffixes=("_before", "_after")))Merging on the index
Set left_index=True or right_index=True to use the index as a key. The method df.join(other) is shorthand for a left merge on the index.
Duplicate keys multiply rows
The most damaging merge error is a key that repeats. If a key value appears twice in the left table and three times in the right, the result has six rows for that key. Row counts grow with no warning.
import pandas as pd
left = pd.DataFrame({"k": ["a", "a"], "x": [1, 2]})
right = pd.DataFrame({"k": ["a", "a", "a"], "y": [7, 8, 9]})
print(len(left.merge(right, on="k"))) # 6Guard against this with the validate argument. It raises MergeError if the key relationship is not what you declared.
import pandas as pd
left = pd.DataFrame({"k": ["a", "a"], "x": [1, 2]})
right = pd.DataFrame({"k": ["a"], "y": [7]})
try:
left.merge(right, on="k", validate="one_to_one")
except pd.errors.MergeError as err:
print("Caught:", err)Valid options are "one_to_one", "one_to_many", "many_to_one", and "many_to_many". For a lookup table, "many_to_one" states your intent and protects the row count.
Diagnosing unmatched rows
Use indicator=True to add a _merge column that records where each row came from: left_only, right_only, or both.
import pandas as pd
cities = pd.DataFrame({"city": ["Oslo", "Lima"], "region": ["EU", "SA"]})
labels = pd.DataFrame({"region": ["EU"], "label": ["Europe"]})
check = cities.merge(labels, on="region", how="outer", indicator=True)
print(check)
print(check["_merge"].value_counts())Common reasons for left_only rows are trailing spaces, different capitalization, or different dtypes in the key columns (for example "1" as a string against 1 as an integer). Merging a string key against an integer key raises an error in current pandas, but two string columns that differ by whitespace merge without any warning.
Summary of choices
| Goal | Tool |
|---|---|
| Append files with the same columns | `pd.concat([...], ignore_index=True)` |
| Remember which file a row came from | `pd.concat([...], keys=[...])` |
| Add columns that share index labels | `pd.concat([...], axis=1)` or `join` |
| Attach lookup data by a key column | `left.merge(right, on=..., how="left", validate="many_to_one")` |
| Find keys that do not match | `merge(..., how="outer", indicator=True)` |
Exercise
You run orders.merge(customers, on="customer_id"). The orders table has 1,000 rows, but the result has 940 rows. A colleague then tries how="left" and gets 1,000 rows. What explains the difference, and which two arguments would you add to find the problem rows and to guard against rows being duplicated?
Show answer
The default how="inner" drops the 60 orders whose customer_id has no match in customers. The left merge keeps them and fills the customer columns with NaN. Add indicator=True to see the left_only rows, and validate="many_to_one" to raise an error if customers contains a repeated customer_id, which would multiply order rows.
Exercise
What does pd.concat([df1, df2]) do to the index, and how do you get a clean 0..n-1 index?
Show answer
It keeps the original labels from both tables, so labels can repeat. Pass ignore_index=True to renumber the rows from 0 to n-1.