How to Merge Spreadsheets by URL When the Rows Won’t Match

Date:

You have two spreadsheets that share a URL column. You join them, and rows come back “unmatched” even though you can see the same page in both files. Or every row matches, and some of those matches are wrong. Both problems start in the same two places: how the URLs are cleaned, and how the misses are counted.

The short answer: to merge spreadsheets by URL, build a match key that normalizes only what can’t change the page (scheme, host case, a leading www., tracking parameters, a trailing slash), keep the path’s case and its real query parameters, set aside rows with no URL, and let the join itself record what matched. A count of blank cells after the merge is not a count of misses.

Why the same page fails to match, or two pages match

A URL can be written several ways and still open the same page. It can also differ by one character and open a different one. A plain text join knows neither, so it fails in both directions:

URLsWhat a naive join doesWhy it’s wrong
www.example.com/a and example.com/atreats them as differentthe same page never matches
http://…/a and https://…/a/treats them as differentscheme and trailing slash don’t change the page
…/item?id=101 and …/item?id=102one key, if you strip the ? parttwo products become one
…/course/Intro-to-SQL and …/course/intro-to-sqlone key, if you lowercase everythingpaths are case-sensitive, so these can be two pages
two rows with no URLmatched to each otherblanks pair up and make false matches

The first two rows cause the “unmatched” rows you can see with your own eyes. The last three are worse, because the merge looks clean while it quietly joins the wrong records. Lowercasing the whole URL and cutting off the query string are the usual cleaning steps, and they are the ones that cause it.

The URL standard settles the case question: the scheme and host are case-insensitive, the path is not. Query parameters often carry the page’s identity, so only the tracking ones (utm_source, fbclid, gclid and similar) are safe to drop.

Step 1: build a match key that changes form, not the page

Keep the original URL column untouched and add a cleaned key next to it. This function normalizes only what can’t change which page you get:

from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
import pandas as pd

TRACKING = ("utm_", "fbclid", "gclid", "ref", "mc_")

def match_key(url):
    if pd.isna(url) or not str(url).strip():
        return None                      # no URL: never a key that matches other blanks
    p = urlsplit(str(url).strip())
    host = p.netloc.lower().removeprefix("www.")
    query = urlencode(sorted((k, v) for k, v in parse_qsl(p.query)
                             if not k.lower().startswith(TRACKING)))
    path = p.path.rstrip("/") or "/"
    return urlunsplit(("", host, path, query, ""))
Code language: Python (python)

With it, https://www.example.com/course/Intro-to-SQL/?utm_source=news and http://example.com/course/Intro-to-SQL get the same key. /item?id=101 and /item?id=102 stay apart, and so do the two capitalizations of the path. The #fragment is dropped too, since it only points inside a page.

Normalize only what can’t change which page you get.

If your files really do write the same path in two cases and you know they are one page, fix that in the data you control. Don’t fold it into the key for every URL.

Step 2: set rows with no URL aside before joining

pandas treats missing keys as equal to each other. On a test with two URL-less rows in each file, the join paired every blank with every other blank and produced four false matches. An empty string "" used as a key does exactly the same. Pull those rows out first, and review them on their own.

Step 3: refuse duplicate keys

If a key appears twice on one side, it matches every copy on the other, and one row turns into several. Pass validate="one_to_one" and the merge stops with an error instead of copying rows. When it stops, look at the duplicates: they are either a real duplicate in your data or a sign the key is too coarse.

Step 4: let the join report what didn’t match

pandas can record, for every row, whether its key was found on both sides. Ask for it with indicator=True, and use an outer join so rows that exist only in the second file show up as well:

def merge_on_url(left, right, left_col, right_col):
    l = left.assign(match_key=left[left_col].map(match_key))
    r = right.assign(match_key=right[right_col].map(match_key)).drop(columns=[right_col])
    # pandas joins missing keys to each other, so rows without a URL are set aside, not merged
    no_url = pd.concat([l[l["match_key"].isna()].assign(side="left"),
                        r[r["match_key"].isna()].assign(side="right")])
    merged = l.dropna(subset=["match_key"]).merge(
        r.dropna(subset=["match_key"]), on="match_key", how="outer",
        suffixes=("", "_right"), indicator=True, validate="one_to_one")
    return merged, no_url

merged, no_url = merge_on_url(listing, details, "url", "page_url")
print(merged["_merge"].value_counts())
unmatched = merged[merged["_merge"] != "both"]
Code language: Python (python)

The _merge column says both, left_only or right_only for every row. That column is your unmatched report, written by the join itself.

Many merge scripts skip it and guess instead: after joining, they flag a row as unmatched when the columns that came from the second file are empty. A script we checked did exactly that on two 546-row files and reported 5 unmatched rows. All 546 had matched. Only one column name, duration, appeared in both files, so it was the only column pandas renamed with the second file’s suffix, and the check looked at suffixed columns only. “Unmatched” really meant “this one cell is blank.”

Bar chart from merging two spreadsheets by URL, comparing two ways of counting rows that failed to match. A report that guessed misses from blank cells said 5 rows were unmatched, marked as wrong. The join's built-in indicator column recorded 0 unmatched rows, because all 546 rows matched on both sides. The 5 reported rows had matched; they were the 5 rows with a blank cell in one column of the second file.

The guess can also fail the other way. When the two files share no column names at all, nothing gets a suffix, and “every one of zero columns is empty” is true for every row. On a three-row test, all 3 rows were reported unmatched and all 3 had matched.

A blank cell after a merge tells you about the data, not about the match.

Step 5: read the misses that are left

Once _merge is in place, open the left_only and right_only rows side by side and compare their keys. What remains is usually one of three things: a page that is genuinely missing from one export, a URL that redirects to a new address, or a parameter that should have been treated as tracking. Fix the cause, re-run, and the counts should move for a reason you can name.

Doing it in Excel or Google Sheets

No Python is needed for any of this. Build the cleaned key in a helper column in both sheets, so you can see exactly what each URL became, then look it up with XLOOKUP or VLOOKUP. A key that isn’t found returns #N/A; a key that is found but points at an empty cell returns an empty or zero value. Count the #N/A results to find real misses, and never count blanks. That is the spreadsheet version of the blank-cell trap above, and it is just as easy to fall into.

A report is a claim, and the join’s own record is the evidence, much like a success message that isn’t confirmation.

Checklist before you trust the merge

  • Lowercase the scheme and host, drop www., the fragment, tracking parameters and one trailing slash.
  • Leave the path’s case and the real query parameters alone.
  • Set rows with no URL aside; never let blank keys join.
  • Use validate="one_to_one" so duplicate keys stop the merge.
  • Count misses from indicator=True (or #N/A in a sheet), never from empty cells.
  • Read every remaining left_only and right_only row before calling it a real gap.

Frequently Asked Questions

Why did my merge produce more rows than my input?

A key that appears more than once on either side matches every copy, so one row can become several. Blank keys are a common cause, because pandas treats missing keys as equal to each other. Add validate="one_to_one" to stop the merge when that happens, and set rows without a key aside before merging.

What about URLs that redirect to a new address?

A cleaned key can’t see a redirect, because the old and new addresses really are different strings. If one file is older than the other, map old URLs to their new ones before building the key: use the site’s redirect list if you have it, or request each unmatched URL once and record where it ends up. Then key on the final address, and keep the original column so you can see which rows were remapped.

What if the two files share no URL at all?

Then you’re deciding whether two records describe the same thing from their content: titles, codes, prices. That’s record matching rather than a join, and it needs rules and review rather than a key. For a worked example, see how to tell the same course on two stores from a coincidence.

Share post:

Subscribe

Popular

More like this
Related

WooCommerce Search by SKU or ISBN Finds Nothing? It Never Looks There

A shopper types the SKU from your catalog, or the ISBN printed on the back of a book, and gets "No products were found". The product is right there, and the number is on its page. Search simply never reads that part of the product.

Computer Slow but CPU and Memory Look Normal? Check the Handle Count

Chrome takes a minute to open, or doesn't open at all. Every click waits. You open Task Manager expecting to find the culprit, and it tells you everything is fine. Here is the number that isn't, and the fix that takes two minutes.

Kernel-Power 41 Tells You Your PC Restarted, Not Why

Your PC restarts with no blue screen, and the only clue is a critical event saying it didn't shut down cleanly. Here is how to get from that event to a short list of suspects.

Set Up WordPress SMTP Without a Plugin, Even on a Multisite Network

WordPress mail goes out as wordpress@ your domain, from the web server, and lands in spam. An SMTP plugin fixes that. So do about twenty lines of code, and on a network of sites the code can give every site its own mailbox and its own password.