← Blog
Two rows of illustrated inventory tags on yellow paper, with loose tags beside the matching pairs.
Published on

Compare two CSV files by ID with Python

Yesterday’s product catalog and today’s both contain three rows. Did anything change? A row count misses the price correction and the product swap. To compare two CSV files in Python, match records by a stable product ID, then compare the fields that matter within each match. The result is a short file a catalog owner can use to review changes.

Decide what counts as a change

Use two complete snapshots of the same catalog, with the same supplier, currency and product filters. A missing ID in today’s export means “removed” only if today’s file covers the full catalog. If the supplier sends only changed records, an absent ID tells you nothing about whether that product is still available. Hold an unexpectedly empty or partial delivery until the source owner confirms it.

For this example, the product ID identifies a record and the price is the only field under review. Read IDs as text so that 001 stays distinct from 1. Prices use whole US cents without separators or padded zeros. A free product has a price of 0. A blank price needs a decision from the supplier. If your export mixes currencies, agree on a currency field and comparison rule before using the example.

Read the two exports side by side

Save the older snapshot as previous.csv.

product_id,price_cents
001,450
002,800
003,250

Save the newer snapshot as current.csv. Product 003 now appears first. Its price still matches.

product_id,price_cents
003,250
004,600
001,475

Read down the IDs once before writing any code. Product 001 costs 25 cents more. Product 002 appears only in the older file, and product 004 appears only in the newer one. Those are the three differences a reviewer should see. A line-by-line file comparison would also flag product 003 simply because it moved.

Match rows by ID with pandas

The following Python example assumes pandas is available and both files are in the working directory. It keeps the IDs and prices as text, rejects ambiguous keys, and uses an outer merge so products that appear on only one side survive the comparison. The example uses a new output filename in the working directory. Running it again replaces that output.

import pandas as pd

def read_catalog(path):
    data = pd.read_csv(path, dtype=str, keep_default_na=False,
                       skip_blank_lines=False, encoding="utf-8-sig")
    data = data[["product_id", "price_cents"]].copy()
    ids = data["product_id"]
    if ids.str.strip().eq("").any() or ids.duplicated().any():
        raise ValueError(f"{path}: blank or duplicate product ID")
    if ids.ne(ids.str.strip()).any():
        raise ValueError(f"{path}: spaces around a product ID")
    if not data["price_cents"].str.fullmatch(r"0|[1-9][0-9]*").all():
        raise ValueError(f"{path}: expected whole cents, such as 450")
    return data

old = read_catalog("previous.csv")
new = read_catalog("current.csv")
rows = old.merge(new, on="product_id", how="outer",
                 suffixes=("_old", "_new"), indicator=True,
                 validate="one_to_one")
rows["status"] = rows["_merge"].map({
    "left_only": "removed", "right_only": "added", "both": "unchanged"
}).astype("object")
changed = (rows["_merge"] == "both") & (
    rows["price_cents_old"] != rows["price_cents_new"]
)
rows.loc[changed, "status"] = "changed"
cols = ["product_id", "status", "price_cents_old", "price_cents_new"]
diff = rows.loc[rows["status"] != "unchanged", cols].sort_values("product_id")
diff.to_csv("catalog-diff.csv", index=False)

The merge indicator records where each ID appeared. For an ID present in both files, the code compares the two price values. This works as a text comparison because the input rule allows only one spelling for each price. If one source writes dollars as 4.50 and the other writes cents as 450, agree on a conversion before comparing them. The pandas merge reference explains the indicator and the one-to-one key check.

Review the differences before acting on them

For the inputs above, the expected contents of catalog-diff.csv are:

product_id,status,price_cents_old,price_cents_new
001,changed,450,475
002,removed,800,
004,added,,600

A blank old price for 004 means there was no older record. The blank new price for 002 means there was no newer record. Neither blank means a price of zero. Product 003 drops out of the review file because its price stayed the same. To reconcile the counts, start with three older products, subtract one removal and add one new product. The total is three again.

If an ID appears twice in either input, stop and check what one row represents. A supplier might list one row per product and warehouse. In that case, ask whether the comparison should use both fields as its key. Silently keeping the first row can hide a real price change. The Python ETL guide covers input validation before a database load. The comparison here ends with a review file.

Keep enough evidence to explain a rerun

Keep each pair of dated snapshots together with its difference file. Record the source, the reporting period and any corrections. If a supplier replaces yesterday’s export, keep the first comparison identifiable so the reviewer can explain why the result changed. When opening the CSV in a spreadsheet, import the ID column as text. For a recurring workbook with typed columns and a summary, use the Python Excel report guide.

An occasional comparison can run on a laptop. A CPU VM becomes useful when a team needs the same environment to collect approved inputs and run the comparison unattended. Both inputs and the merged data occupy memory together. Use a representative pair of real exports to measure peak memory, disk space and elapsed time before choosing a VM in the CPU buying guide.

The expected differences above were checked against the six example rows. The Python snippet, scheduled runs, database integration and cloud deployment were not tested for this guide.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.