TECHNOLOGIESTieInn Technologies

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 _x and _y; set suffixes= 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 →

Questions

Open in Code Lab5 free questions
5 questions

    Merging and joining DataFrames

  1. Question 1easy

    What kind of join does a.merge(b, on="id") do if you don't pass how?

  2. Merging and joining DataFrames

  3. Question 2medium

    Both DataFrames have a column status that isn't a key. What happens after merging?

  4. Merging and joining DataFrames

  5. 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")))
  6. Merging and joining DataFrames

  7. 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())
  8. Merging and joining DataFrames

  9. Question 5hard

    After lines = order_items.merge(orders, on="order_id"), why is lines["amount"].sum() far bigger than orders["amount"].sum()?

9 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.