Merging and joining DataFrames
Python · 14 questions
Short notes
Key idea
merge joins two DataFrames on a key column, like a SQL join. concat stacks DataFrames on top of each other.
Syntax
pd.merge(orders, customers, on="customer_id", how="left")
orders.merge(customers, left_on="cust", right_on="customer_id")
pd.concat([jan, feb], ignore_index=True)
how: "inner" (default, matches only), "left", "right", "outer".
Example
m = orders.merge(customers, on="customer_id", how="left",
indicator=True, validate="many_to_one")
print(m["_merge"].value_counts())
indicator=True adds a column saying where each row came from; validate raises an error if customers has duplicate keys.
Traps
- Duplicate keys multiply rows, just as in SQL. Check
len()before and after. - Key types must match:
101(int) and"101"(text) never join. - Same column names on both sides get
_xand_y; setsuffixes=to readable names. - Inner is the default. Forgetting
how="left"silently drops unmatched rows.
Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →
- Question 1easy
What kind of join does
a.merge(b, on="id")do if you don't passhow? - Question 2medium
Both DataFrames have a column
statusthat isn't a key. What happens after merging? - Question 3medium
40 customers placed 80 orders, and 9 customers never ordered. What does this print?
print(len(customers.merge(orders, on="customer_id", how="left")))
- Question 4medium
What does this print?
m = customers.merge(orders[["customer_id"]].drop_duplicates(), on="customer_id", how="left", indicator=True) print((m["_merge"] == "left_only").sum()) - Question 5hard
After
lines = order_items.merge(orders, on="order_id"), why islines["amount"].sum()far bigger thanorders["amount"].sum()?
Merging and joining DataFrames
Merging and joining DataFrames
Merging and joining DataFrames
Merging and joining DataFrames
Merging and joining DataFrames
9 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.