Disclosure: I built the Apify Actor mentioned near the end of this post.

When drop_duplicates() fails or leaves duplicates in scraped data, it is almost always one of four things: a column holds lists or dicts (TypeError: unhashable type: 'list'), the same ID arrives as both 101 and "101", text differs by a trailing space, or the same page has several URL spellings. Fix it by deduplicating on hashable key columns (or a JSON string of the row), casting IDs to one type, stripping text, and building a normalized URL key. Pandas itself is doing exactly what it says: it compares values, and these values really are different.

Below is a small, reproducible example of each case, then how to merge several scraper runs and keep only the items you have not seen before.

Why does drop_duplicates raise "unhashable type: 'list'"?

Scraper output is JSON, and JSON rows often carry lists (tags, image URLs, categories) or nested objects (salary, address). Pandas hashes each value to compare rows, and Python lists and dicts cannot be hashed. With no subset, drop_duplicates() looks at every column, so a single list column breaks the whole call.

Here is a made-up five-row "job scraper" result that has every problem in this post:

import pandas as pd rows = [ {"url": "https://www.example.com/jobs/101", "title": "Data Analyst", "jobId": 101, "tags": ["sql", "python"]}, {"url": "https://www.example.com/jobs/101", "title": "Data Analyst", "jobId": 101, "tags": ["sql", "python"]}, {"url": "https://www.example.com/jobs/102/", "title": "Backend Engineer ", "jobId": "102", "tags": ["go"]}, {"url": "https://example.com/jobs/102?utm_source=feed", "title": "Backend Engineer", "jobId": 102, "tags": ["go"]}, {"url": "http://WWW.EXAMPLE.COM/jobs/103#apply", "title": "Product Designer", "jobId": 103, "tags": []}, ] df = pd.DataFrame(rows) try: df.drop_duplicates() except TypeError as e: print("TypeError:", e) print(len(df.drop_duplicates(subset=["url", "title", "jobId"])), "rows after subset dedup") print(df["jobId"].map(type).value_counts().to_dict()) 

Output (pandas 2.3.3, run on 2026-12-01):

TypeError: unhashable type: 'list' 4 rows after subset dedup {<class 'int'>: 4, <class 'str'>: 1} 

Passing subset= with only hashable columns stops the error. But it only removed the exact copy of job 101. Jobs 102 and 103 are three listings of two jobs, and pandas kept all of them. The last line shows one reason: jobId is an int in four rows and a string in one.

How do I dedup whole rows that contain lists or dicts?

If you really want "identical in every field", turn each row into a JSON string and dedup on that:

import json def row_key(row, ignore=()): d = {k: v for k, v in row.items() if k not in ignore} return json.dumps(d, sort_keys=True, ensure_ascii=False, default=str) df["_key"] = [row_key(r) for r in df.to_dict("records")] print(len(df.drop_duplicates(subset="_key")), "rows after whole-row dedup") 
4 rows after whole-row dedup 

ignore is there for fields that change on every run, such as a scrapedAt timestamp. Leave those in and no two runs will ever share a key.

Why json.dumps(..., sort_keys=True) and not the common df.astype(str).drop_duplicates() answer? Because scrapers do not promise key order inside nested objects:

pay = pd.DataFrame({"salary": [{"min": 50, "max": 70}, {"max": 70, "min": 50}]}) print(len(pay.astype(str).drop_duplicates()), "rows with astype(str)") print(len(pay["salary"].map(lambda v: json.dumps(v, sort_keys=True)).drop_duplicates()), "row with json.dumps(sort_keys=True)") 
2 rows with astype(str) 1 row with json.dumps(sort_keys=True) 

Same salary, two "different" strings. Converting lists to tuples (df["tags"].apply(tuple)) also works for flat lists, but not for lists of dicts.

Why are rows that look the same not removed?

Because they are not the same value. The usual suspects in scraped data:

Looks like Actually Fix
101 and 101 int 101 and string "101" df["jobId"] = df["jobId"].astype(str)
Backend Engineer one has a trailing space df["title"] = df["title"].str.strip() (add .str.lower() if case does not matter)
one job page www. vs no www., http vs https, trailing /, ?utm_source=, #apply normalize into a key column (below)
same item a field that changes every run (scrapedAt, position, price) leave it out of subset

How do I normalize URLs before dropping duplicates?

Do not overwrite the URL. Add a key column next to it and dedup on that:

from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode TRACKING = {"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "gclid", "fbclid"} def url_key(u): p = urlsplit(u.strip()) host = p.netloc.lower() if host.startswith("www."): host = host[4:] path = p.path.rstrip("/") or "/" query = urlencode(sorted((k, v) for k, v in parse_qsl(p.query) if k.lower() not in TRACKING)) return urlunsplit(("https", host, path, query, "")) df["url_key"] = df["url"].map(url_key) df["jobId"] = df["jobId"].astype(str) df["title"] = df["title"].str.strip() clean = df.drop_duplicates(subset="url_key").drop(columns="_key") print(clean[["url_key", "title", "jobId"]].to_string(index=False)) 
 url_key title jobId https://example.com/jobs/101 Data Analyst 101 https://example.com/jobs/102 Backend Engineer 102 https://example.com/jobs/103 Product Designer 103 

Five rows, three jobs. Two warnings about this function:

  • Only drop parameters you know are tracking. Many sites put the item ID in the query string (/item?id=1001). Deleting the whole query would merge different products into one. That is why it removes a fixed list and sorts the rest.
  • Lowercase the host, not the path. Hostnames are case-insensitive; paths often are not.

Also decide which copy wins. keep="first" (the default) keeps the earliest row; if you want the freshest data, sort by scrape time and use keep="last".

How do I merge several Apify runs and remove duplicates?

If your scraper runs on Apify, each run writes a dataset, and the items endpoint returns it as JSON: https://api.apify.com/v2/datasets/<datasetId>/items?format=json&clean=true. clean=true skips empty items and hidden fields (names starting with #). Per the API reference, there is no limit on how many items one response returns.

Apify's general resource access docs list "Restricted" as the default, and restricted datasets need your API token. The two below are small demo datasets set to "Anyone with ID can read", so this runs without an account:

import json import urllib.request import pandas as pd def dataset_items(dataset_id, token=None): url = f"https://api.apify.com/v2/datasets/{dataset_id}/items?format=json&clean=true" req = urllib.request.Request(url) if token: # needed for private datasets req.add_header("Authorization", f"Bearer {token}") with urllib.request.urlopen(req, timeout=60) as r: return json.load(r) frames = [] for ds in ["knjG69HLEYFoQcTTT", "XYhmJmrqYKJ1f4HSD"]: # run 1, then run 2 part = pd.DataFrame(dataset_items(ds)) part["datasetId"] = ds frames.append(part) print(ds, len(part), "items") merged = pd.concat(frames, ignore_index=True) unique = merged.drop_duplicates(subset="url", keep="first") print(len(merged), "read,", len(unique), "unique") print(unique[["url", "title", "datasetId"]].to_string(index=False)) 

Output on 2026-12-01:

knjG69HLEYFoQcTTT 5 items XYhmJmrqYKJ1f4HSD 5 items 10 read, 7 unique url title datasetId https://www.example.com/jobs/101 Data Analyst knjG69HLEYFoQcTTT https://www.example.com/jobs/102 Backend Engineer knjG69HLEYFoQcTTT https://www.example.com/jobs/103 Product Designer knjG69HLEYFoQcTTT https://www.example.com/jobs/104 Support Specialist knjG69HLEYFoQcTTT https://www.example.com/jobs/105 QA Engineer knjG69HLEYFoQcTTT https://www.example.com/jobs/106 Data Engineer XYhmJmrqYKJ1f4HSD https://www.example.com/jobs/107 Sales Manager XYhmJmrqYKJ1f4HSD 

The second run repeated jobs 104 and 105 and listed 106 twice; all three copies are gone. Keeping datasetId tells you which run each item first appeared in. (The demo URLs are already clean; with real data, dedup on url_key from the previous section instead of url.)

How do I keep only items that were not in an earlier run?

For a scheduled scraper you usually want "what is new since last time", not one merged list. Keep the keys you have already delivered and filter against them:

from pathlib import Path SEEN = Path("seen_urls.txt") def only_new(df, key="url"): seen = set(SEEN.read_text().split()) if SEEN.exists() else set() fresh = df[~df[key].isin(seen)].drop_duplicates(subset=key) SEEN.write_text("\n".join(sorted(seen | set(fresh[key]))) + "\n") return fresh week1 = pd.DataFrame(dataset_items("knjG69HLEYFoQcTTT")) week2 = pd.DataFrame(dataset_items("XYhmJmrqYKJ1f4HSD")) print("run 1 new:", list(only_new(week1)["url"].str[-3:])) print("run 2 new:", list(only_new(week2)["url"].str[-3:])) print("run 2 again:", list(only_new(week2)["url"].str[-3:])) 
run 1 new: ['101', '102', '103', '104', '105'] run 2 new: ['106', '107'] run 2 again: [] 

Things that bite once this runs unattended:

  • Save the seen keys after the next step succeeds, not before. Here they are written immediately; if your e-mail or Sheets step then fails, those items are "seen" and never sent.
  • The file only grows. Store a last-seen date per key and drop old ones, or a few months of a busy feed becomes millions of lines.
  • Two overlapping runs can both read the old file and both deliver the same item. Run them one at a time, or lock the file.
  • Changing the key (say from url to url_key) makes every item new again. Start a fresh file on purpose when you do it.

Is there a hosted version for Apify datasets?

If your data is already in Apify datasets and you would rather not host the script and the seen-keys file, I built an Actor for this: Merge & Dedup Datasets – Keep Only New Items. It is an independent tool, not an official Apify one. It reads the datasets you pick, keeps the first copy of each duplicate by the fields you choose, and with Only items not seen in earlier runs on, remembers delivered keys in a key-value store in your own account.

Leave Datasets empty and click Start: the prefilled input, {"dedupFields": ["url"]}, then merges the same two demo datasets by url and returns the same 7 items as the pandas version above. Demo items are marked isDemoData: true and are not charged; you pay only the US$0.0005 run start.

To get only new items after every run of a scraper, connect it as an integration that fires when the scraper's run succeeds, with this input:

{ "datasetIds": ["{{resource.defaultDatasetId}}"], "dedupFields": ["url"], "onlyNewItems": true, "memoryName": "my-scraper-new-items" } 

{{resource.defaultDatasetId}} becomes the dataset of the run that just finished. The datasets do not have to be public: the Actor can read any dataset in your account (or shared with you) whose ID you pass in its input, whether you pick it in the form or send the ID through the API or an integration. Each run returns only items whose url it has not returned before under that memory name, so the second run over the same data returns 0 items, and the run's status message says how many were duplicates and how many were seen in earlier runs.

What it does and does not do (from its README):

  • Price: US$0.50 per 1,000 items returned plus US$0.0005 per run start. Duplicates, already-seen items and demo items are not charged. Apify's free plan (US$5 of usage a month) covers about 10,000 returned items.
  • Exact matching only. Values must match exactly, including type (1 vs "1") and letter case. It does not normalize URLs or strip text, so the traps in the first half of this post still apply: clean the field in your scraper, or dedup on a field that is already stable, such as an ID.
  • Up to 100 datasets per run; items must be JSON objects; returns roughly 10–15 items per second, and a run lasts at most about 55 minutes.
  • Only reads the datasets you give it (it runs with Apify's limited permissions).

FAQ

Why does drop_duplicates not remove duplicates in my DataFrame?

Because the rows differ somewhere you are not looking: an int vs a string ID, a trailing space, a different URL spelling, or a timestamp column. Print the suspected pair with df.loc[[i, j]].T and compare each value with repr(). Then fix the column or leave it out of subset.

How do I fix "TypeError: unhashable type: 'list'" in drop_duplicates?

Pass subset= with only hashable columns, or build a key column with json.dumps(row, sort_keys=True) and dedup on it. For a single flat list column, df["tags"].apply(tuple) is enough. The same fix applies to unhashable type: 'dict'.

Does drop_duplicates treat NaN values as equal?

Yes. Two rows with NaN in the same column count as duplicates in that column. That surprises people who expect SQL-style NULL != NULL behaviour.

Should I dedup in the scraper or afterwards?

Both, for different reasons. Skipping known URLs in the crawler saves requests. Deduplicating the output catches what the crawler cannot know, such as the same item reached through two listing pages, or items seen in last week's run.

Can I read an Apify dataset without an API token?

Only if its owner's account (or that dataset) is set to "Anyone with ID can read". Apify's docs list Restricted as the default setting; then you need a token in the Authorization: Bearer header. The items endpoint is the same either way.

Which one has bitten you more often: the unhashable list error, or duplicates that "look the same" but stay?

Disclosure: I built the Apify Actor mentioned in this post.