Sub topic 15
Combining tables with concat and merge
This chapter assumes you can build a DataFrame, select columns, and read the NaN that index alignment produces. Two functions cover most table combining. pd.concat stacks tables along an axis and aligns them on the index. DataFrame.merge joins tables on key columns, like a SQL join.
Stacking with concat
Use concat when the tables have the same kind of data and you want more rows (or more columns) from the same index space.
import pandas as pd
q1 = pd.DataFrame({"city": ["Oslo", "Lima"], "sales": [5, 8]})
q2 = pd.DataFrame({"city": ["Pune", "Rome"], "sales": [3, 6]})
both = pd.concat([q1, q2], ignore_index=True)
print(both)Without ignore_index=True, the result keeps the original labels, so the index would read 0, 1, 0, 1. Duplicate labels make later loc selection return several rows. Pass ignore_index=True unless the labels carry meaning.
If the columns differ, concat takes the union of them and fills the gaps with NaN. This is index alignment applied to column labels. Pass join="inner" to keep only the shared columns.
Joining with merge
Use merge when two tables describe the same entities through a shared key.
import pandas as pd
cities = pd.DataFrame({"city": ["Oslo", "Lima", "Pune"], "region": ["EU", "SA", "AS"]})
labels = pd.DataFrame({"region": ["EU", "AS"], "label": ["Europe", "Asia"]})
merged = cities.merge(labels, on="region", how="left")
print(merged)The how argument decides which rows survive:
| `how` | Rows kept |
|---|---|
| `inner` (default) | Keys present in both tables |
| `left` | Every left row, with NaN where the right has no match |
| `right` | Every right row |
| `outer` | Every row from both tables |
In the example, Lima has region SA, which labels lacks. A left merge keeps Lima and puts NaN in label. The default inner join would drop Lima without any warning.
Common errors
- Duplicate keys multiply rows. If a key appears twice on the right, each left row with that key appears twice. Pass
validate="many_to_one"to raise an error when this happens. - Different key names. Use
left_on="a", right_on="b". Both columns then appear in the result, so drop one. - Overlapping column names. Non-key columns with the same name get the suffixes
_xand_y. Setsuffixes=("_left", "_right")to choose better ones. - Silent row loss. Compare
len()before and after, or useindicator=Trueto add a_mergecolumn showing where each row came from.
Exercise
You run cities.merge(labels, on="region") with no how argument, and the result has fewer rows than cities. Why, and how do you keep every city?
Show answer
The default is how="inner", so cities whose region is missing from labels are dropped. Use how="left" to keep every row of cities, with NaN in the columns that come from labels.