TECHNOLOGIESTieInn Technologies

Comparing two tables with pandas

Data Quality Automation with Python · 7 questions

Short notes

Key idea

pandas compares tables that live in different systems or files, and inside automated tests. An outer merge with indicator=True finds missing and extra rows; duplicated(keep=False) finds duplicates; merged _src/_tgt columns or DataFrame.compare find changed values; assert_frame_equal gives tests a strict pass or fail.

Syntax

m = src.merge(tgt, on="order_id", how="outer",
              indicator=True, suffixes=("_src", "_tgt"))
missing = m[m["_merge"] == "left_only"]
extra = m[m["_merge"] == "right_only"]
dups = tgt[tgt.duplicated("order_id", keep=False)]
both = m[m["_merge"] == "both"]
changed = both[both["amount_src"] != both["amount_tgt"]]

from pandas.testing import assert_frame_equal
assert_frame_equal(a, b, check_dtype=False)

Example

Shop: left_only gives 57 and 75; duplicated gives 46 and 47 (runs 3 and 4); the amount comparison gives 66. Total difference after rounding: 14214.95.

Traps

  • Only len(): duplicates and gaps cancel out.
  • Inner merges drop the rows you want.
  • compare needs the same index and columns, and no duplicate keys.
  • <NA> != <NA> isn't True; fill or compare explicitly.
  • Round money before comparing.

Want the full lesson with step-by-step examples, a project and a certificate? Data Quality Automation with Python course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Comparing two tables with pandas

  1. Question 1easy

    What does this print?

    print(len(dw_orders) - dw_orders["order_id"].nunique())
  2. Comparing two tables with pandas

  3. Question 2medium

    What does this print?

    m = orders.merge(dw_orders, on="order_id", how="outer", indicator=True)
    print((m["_merge"] == "left_only").sum())
  4. Comparing two tables with pandas

  5. Question 3medium

    src.compare(tgt) raises an error. Which preparation is most likely missing?

  6. Comparing two tables with pandas

  7. Question 4medium

    Two DataFrames hold the same numbers, but one column is int64 in one frame and float64 in the other. What does assert_frame_equal(a, b) do?

  8. Comparing two tables with pandas

  9. Question 5easy

    What does this print?

    print(round(dw_orders["amount"].sum() - orders["amount"].sum(), 2))

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

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