ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Pandas Tutorial• 7 min read

Merging, Joining & Concatenating DataFrames

SQL-style inner, left, right, and outer joins with merge() and concat()

Combining data from disparate sources is achieved using pd.merge() for relational key-based joins and pd.concat() for axis-aligned binding.

Join Types in pd.merge()

how="inner" (Default): Returns only records with matching keys in both tables.

how="left": Preserves all rows from the left table, filling unmatched right columns with NaN.

how="right": Preserves all rows from the right table.

how="outer": Full outer join, retaining all rows from both tables.

pd.concat([df1, df2], axis=0): Stacks DataFrames vertically (unions rows).

Relational Left Join with pd.merge
import pandas as pd

users = pd.DataFrame({
    "user_id": [1, 2, 3],
    "name": ["Alice", "Bob", "Charlie"]
})

orders = pd.DataFrame({
    "order_id": [101, 102, 103],
    "user_id": [1, 2, 1],
    "amount": [99.50, 45.00, 150.25]
})

# Left join users onto their orders
merged = pd.merge(orders, users, on="user_id", how="left")
print("Merged Orders with User Details:
", merged)
pd.merge operates exactly like a SQL JOIN on matching foreign keys.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which join type in `pd.merge()` preserves all records from the left DataFrame regardless of whether a match exists in the right DataFrame?