AdvancedMerging, Joining & Reshaping
Combining multiple DataFrames, and pivoting between long and wide.
import pandas as pd
orders = pd.DataFrame({"order_id": [1, 2, 3], "customer_id": [10, 20, 30]})
customers = pd.DataFrame({"customer_id": [10, 20, 40], "name": ["Alice", "Bob", "Carol"]})
print(pd.merge(orders, customers, on="customer_id", how="inner")) # only matches in both
print(pd.merge(orders, customers, on="customer_id", how="left")) # keep every order
| how= | Keeps | Example |
|---|
inner
| only rows with a match on both sides | left has keys 1,2; right has 2,3 → result has just key 2 |
left
| every row from the left table, even without a match | key 1 (no match) still appears, with NaN for the right columns |
right
| every row from the right table | key 3 (no match on left) still appears, with NaN for the left columns |
outer
| every row from both, matched where possible | keys 1, 2, 3 all appear; unmatched sides are NaN |
import pandas as pd
a = pd.DataFrame({"x": [1, 2, 3]})
b = pd.DataFrame({"x": [4, 5]})
print(pd.concat([a, b], ignore_index=True)) # stack rows, fresh index
wide = pd.DataFrame({"id": [1, 2], "jan": [10, 20], "feb": [15, 25]})
long = wide.melt(id_vars=["id"], var_name="month", value_name="sales")
print(long) # wide -> long
print(long.pivot(index="id", columns="month", values="sales")) # long -> wide, back again
📝 Note: concat stacks DataFrames as-is (rows or columns); merge/join combine them based on matching key VALUES, like a SQL join.
Now practice it
Exercises that use what this lesson just covered.