Pandas Merging Data

Join two DataFrames like SQL.

✍️ 3 exercises + code challenge in this lesson

pd.merge(left, right, on="key") combines DataFrames on a shared column, like an SQL join.

  • how="inner" (default), "left", "right", "outer"
  • pd.concat([df1, df2]) stacks DataFrames on top of each other.

Key Takeaways: Pandas Merging Data

Mastering Pandas Merging Data helps you write clean and reliable Pandas code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Pandas Merging Data Code Example

Pandas
import pandas as pd

customers = pd.DataFrame({"id": [1, 2, 3], "name": ["Ali", "Sara", "Usman"]})
orders = pd.DataFrame({"customer_id": [1, 1, 3], "amount": [5000, 1200, 800]})

merged = pd.merge(orders, customers, left_on="customer_id", right_on="id")
print(merged[["name", "amount"]])
print(merged.groupby("name")["amount"].sum().to_dict())
Output
name  amount
0    Ali    5000
1    Ali    1200
2  Usman     800
{'Ali': 6200, 'Usman': 800}
Free sign-in required · Google login available

Pandas Merging Data Practice Exercises

Check what you learned in “Pandas Merging Data”.

/ 3 solved
Fill in the blank

Join two DataFrames on a shared column.

pd.(orders, customers, on="id")
✓ Correct! Not quite. Try again.
Multiple choice

Which "how" keeps all rows from the left DataFrame?

✓ Correct! Not quite. Try again.
Code challenge

Merge orders with customers on "id" and print the names of customers who ordered, as a list.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services