# Merge & Dedupe Datasets: CSV, JSON, Excel Converter (`4b47/merge-dedupe-datasets`) Actor

Merge Apify datasets and CSV, JSON or JSON Lines files into one clean table. Remove duplicates by any fields (exact or fuzzy: case, accents, URLs, phones), rename and pick columns, export to CSV, Excel, JSON. Streams millions of rows. $0.10 per 1,000 rows.

- **URL**: https://apify.com/4b47/merge-dedupe-datasets.md
- **Developed by:** [Kacper Gumieniuk](https://apify.com/4b47) (community)
- **Categories:** Developer tools, Integrations, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.10 / 1,000 row in the results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

**Merge & Dedupe Datasets combines Apify datasets and CSV, JSON or JSON Lines files into one clean table.** It removes
duplicates by the fields you choose (exact, or **normalized**: case, accents, punctuation, `www`/`https`/trailing
slashes, `utm_` tracking, phone formats), renames and picks columns, and writes the result to a dataset plus
**CSV, Excel (XLSX), JSON and JSON Lines files**. It streams page by page, so a million-row merge fits in the default 1 GB of
memory.

**Try it now:** press **Start**. The prefilled input merges two public country lists (a CSV and a CSV with other
column names), renames the columns to match, removes 249 duplicates and gives you a 249-row dataset, CSV and Excel
file in a few seconds for about $0.03. Price: **$0.10 per 1,000 rows in the result**. Duplicates, filtered rows and
failed sources are free. Apify's free plan ($5 of monthly credit) covers about **49,000 result rows a month**.

### Use cases

- **Merge runs of a scraper:** combine yesterday's and today's datasets (or 20 parallel runs) into one table without
  repeats. *Keep last* keeps the freshest copy of each item.
- **Only new items for scheduled pipelines:** turn on *Only new items* and attach the actor to your scraper's runs;
  each run outputs only rows you have never received before, ready for Slack, Sheets or a CRM. Already-seen rows are
  free.
- **Delta between two runs (no setup):** put today's dataset in *Datasets* and yesterday's in *Compare with datasets*:
  you get only the rows that are new today. Ideal before "append to Google Sheets" steps in n8n or Make, which
  otherwise create duplicates. Matched by your dedupe fields; skipped rows are free.
- **Clean lead or product lists:** dedupe by website, email or phone even when they are written differently
  (`HTTPS://www.acme.com/` and `acme.com` match; `+1 (415) 555-0100` and `14155550100` match).
- **Convert formats:** dataset → Excel or CSV with nested fields flattened into columns; CSV/TSV/JSON/JSONL files →
  an Apify dataset you can query through the API.
- **Combine sources with different column names:** rename `link` to `url` in one source and dedupe across both.
- **Prepare data for AI agents and LLMs:** drop heavy fields (HTML, screenshots), keep the columns that matter and
  hand over one compact file.

### How to use Merge & Dedupe Datasets

1. Pick datasets in **Datasets** (from your storage or past runs) and/or paste **File URLs**: JSON, JSON Lines, CSV or
   TSV (gzipped too), Apify API item URLs with your token, or Google Sheets shared as "anyone with the link".
2. Put the identity of a row into **Deduplicate by fields** (e.g. `url`, or `name` + `city`). Leave it empty to remove
   rows that are identical in every field.
3. Optionally **rename**, **keep only** or **remove** fields, and choose **Output formats**.
4. Press **Start**. The run's **Output** tab links the dataset and the files (`merged.csv`, `merged.xlsx`, ...); the
   `SUMMARY` record shows rows read, duplicates and errors per source.
5. To process every run of another actor automatically: open that actor → **Integrations** → *Connect Actor or Task*
   → this actor, with input `{"datasetIds": ["{{resource.defaultDatasetId}}"], "onlyNewItems": true, ...}`.

The pipeline runs in a fixed order: **rename → required fields → deduplicate → keep/remove fields → flatten**.

### Input

```json
{
  "datasetIds": ["aBcDeFgHiJkLmNoPq", "QrStUvWxYz0123456"],
  "sourceUrls": ["https://example.com/export/products.csv"],
  "renameFields": { "link": "url", "title": "name" },
  "dedupeFields": ["url"],
  "dedupeMode": "normalized",
  "keep": "last",
  "fields": ["url", "name", "price", "seller.name"],
  "outputFormats": ["dataset", "csv", "xlsx"]
}
```

| Field | What it does |
| --- | --- |
| `datasetIds` | Apify datasets, picked in the dataset picker (gives this actor read access to just those datasets). |
| `sourceUrls` | JSON array, JSON Lines, CSV/TSV (delimiter detected), `.gz`; Apify API `.../items?token=` URLs (paged); Google Sheets links. |
| `dedupeFields` | Fields that identify a row; nested paths like `address.city`. Empty = whole-row duplicates. |
| `dedupeMode` | `normalized` (default), `exact` or `none`. |
| `keep` | `first` (default) or `last` occurrence of each duplicate. |
| `renameFields` | `{"old": "new"}`, applied first so sources line up before deduplication. |
| `fields` / `omitFields` | Keep only these fields (in this order) / drop these fields. |
| `requireFields` | Drop rows where any of these is empty (free). |
| `onlyNewItems` + `memoryName` | Skip rows output by earlier runs with the same memory name. |
| `compareDatasetIds`, `compareUrls` | Delta mode: skip rows whose identity is in these previous datasets or files. |
| `outputFormats` | Any of `dataset`, `csv`, `xlsx`, `json`, `jsonl` (one price per row, however many). |
| `arrayFormat` | Arrays in CSV/Excel: `join` (`a; b`), `columns` (`tags/0`, `tags/1`) or `json`. |
| `maxItems`, `addSourceField`, `flattenDataset`, `csvDelimiter`, `inputFormat` | Limits and format details. |

### Output

The dataset holds the merged rows in their original shape (or flattened, with `flattenDataset`). A row from the
advanced example (`examples/input-advanced.json`: two overlapping product exports, `keep: last`, picked fields):

```json
{
  "id": 1,
  "name": "Essence Mascara Lash Princess",
  "brand": "Essence",
  "price": 9.99,
  "tags": ["beauty", "mascara"],
  "dimensions": { "width": 15.14, "height": 13.08, "depth": 22.99 },
  "meta.barcode": "5784719087687",
  "_source": "https://dummyjson.com/products?limit=100"
}
```

The same row in `merged.csv` and `merged.xlsx` (nested fields as `dimensions/width` columns, like Apify's own
export; Excel gets real numbers, a bold frozen header row and no row limit below Excel's 1,048,575):

```
id,name,brand,price,tags,dimensions/width,dimensions/height,dimensions/depth,meta.barcode,_source
1,Essence Mascara Lash Princess,Essence,9.99,beauty; mascara,15.14,13.08,22.99,5784719087687,https://dummyjson.com/products?limit=100
```

The `SUMMARY` record: per source rows read, duplicates, rows without required fields and the error if it failed;
totals; the column list; and a direct link to each file.

### How much does merging cost?

| Event | Price | Example |
| --- | --- | --- |
| Row in the result | **$0.0001** | 10,000 unique rows = **$1**; 1,000 rows = $0.10 |
| Actor start (per GB of run memory) | $0.002 | default 1 GB run = $0.002 |
| Duplicates removed, rows without required fields, already-seen rows (only-new and delta mode), failed sources | free | |

One price per row whether you pick one output format or all five. Platform usage is included. Set a **maximum cost
per run** and the actor stops there, with every file containing exactly the rows you paid for.

### Built not to fail

- **Streams instead of loading everything:** datasets are read 5,000 items per request and files are parsed while
  they download, so memory holds only one 16-byte key per unique row (1 million rows ≈ 400 MB peak).
- **Retries and resume:** 429/5xx answers and timeouts are retried with backoff; a download that breaks mid-file is
  re-opened and continues after the last row read.
- **One bad source does not sink the run:** it is reported in `SUMMARY` and the status message, the other sources are
  merged. The run fails only when every source fails (and then nothing is charged).
- **Clear errors:** "The URL returned a web page, not a data file", "No access to dataset X: select it in the
  Datasets picker", "Line 812 is not valid JSON".
- **Limited permissions:** the actor can read only the datasets you pick and write only its own outputs.

### FAQ

#### What counts as a duplicate in normalized mode?

Text is compared ignoring case, accents, punctuation and extra spaces (`Café Müller, GmbH` = `cafe muller gmbh`).
URLs ignore `http`/`https`, `www.`, a trailing slash, `#fragments` and tracking parameters (`utm_*`, `gclid`, `fbclid`).
Emails are compared lowercased, phone numbers by their digits. Use `exact` for byte-for-byte matching.

#### Why did I get "No access to dataset"?

Datasets must be chosen in the **Datasets** picker: that grants this actor read access to exactly those datasets. A
dataset ID pasted into *File URLs* has no grant. Alternatively paste the dataset's API items URL with your token.

#### How big can the merge be?

Millions of rows. Memory holds ~70 bytes per unique row (1 GB ≈ 3 million unique rows, 4 GB ≈ 15 million); files are
written to disk first (disk = 2× run memory). Excel stops at 1,048,575 rows; CSV/JSON have no limit.

#### Can it remember rows between runs?

Yes: *Only new items* with a *Memory name* stores the identities of output rows in a named key-value store in your
account (`merge-dedupe-memory-<name>`). Delete that store to start over.

#### How do I get only the rows that are new since the last run?

Two ways. **Delta mode** compares with datasets or files you name: put the previous run's dataset (or the Google Sheet
you append to) in *Compare with*. **Only new items** keeps its own memory across scheduled runs, so you never pass the
previous dataset. Both match rows by *Deduplicate by fields*: `url` or `id` for "new items", empty (whole row) for
"new or changed". In n8n, call this actor between the scraper and the *Append row* step, e.g.
`{"datasetIds": ["{{ $json.defaultDatasetId }}"], "compareUrls": ["<your sheet link>"], "dedupeFields": ["url"]}`.

#### Can I call it from code or an AI agent?

Yes: the Apify API (`run-sync-get-dataset-items` returns the merged rows), the JavaScript and Python clients, or the
Apify MCP server. An agent can merge several runs' datasets and receive one deduplicated table.

### Integrations and API

Attach it to any actor or task (Integrations → Connect Actor), schedule it, call it through the API, or connect the
dataset to Google Sheets, Make, Zapier, n8n, Airbyte or webhooks.

### Related actors

- [Career Site Jobs Scraper](https://apify.com/4b47/career-site-jobs): jobs from Greenhouse, Lever, Workday
  and more, with an only-new-jobs mode.
- [Bulk File & Image Downloader](https://apify.com/4b47/bulk-file-downloader): download the images and files
  your datasets link to, as one ZIP.
- [URL to Markdown for LLM & RAG](https://apify.com/4b47/llm-ready-markdown): web pages and PDFs as clean
  Markdown.

Not affiliated with Google or Microsoft; Google Sheets and Excel are their trademarks.

# Actor input Schema

## `datasetIds` (type: `array`):

Apify datasets to merge, in order (pick them from your storage or past runs). Picking a dataset here gives this actor read access to it; nothing else in your account is readable.

## `sourceUrls` (type: `array`):

Data files to merge, one per line: JSON arrays, JSON Lines (.jsonl/.ndjson), CSV or TSV, optionally gzipped. Also works: Apify API items URLs with your token (e.g. https://api.apify.com/v2/datasets/ID/items?token=...; read page by page), Google Sheets links shared as "anyone with the link" (read as CSV). Up to 1,000 sources in total.

## `dedupeFields` (type: `array`):

Rows with the same values in these fields count as duplicates (e.g. url, or name + city). Nested fields: address.city. Empty = whole-row duplicates. Rows where all these fields are empty are always kept.

## `dedupeMode` (type: `string`):

Normalized: ignores case, accents, punctuation and extra spaces; URLs compared without http/https, www, trailing slash and utm\_ tracking; emails lowercased; phone numbers by digits. Exact: values must be identical. Off: just merge and convert.

## `keep` (type: `string`):

First: the earliest row wins (sources are read in order: datasets, then URLs). Last: the latest row wins, e.g. to keep the freshest copy when merging old and new runs.

## `renameFields` (type: `object`):

Old name → new name, applied first (so different sources can share column names before deduplication), e.g. {"link": "url", "address.city": "city"}. If a row already has the new name filled, it is kept.

## `fields` (type: `array`):

Output only these fields, in this order (nested paths allowed). Empty = all fields.

## `omitFields` (type: `array`):

Fields to drop from the output (e.g. large HTML or debug fields).

## `requireFields` (type: `array`):

Drop rows where any of these fields is empty (not charged).

## `outputFormats` (type: `array`):

Where the result goes: the run's dataset, and/or files in the key-value store (merged.csv, merged.xlsx, merged.json, merged.jsonl). The price is per row, however many formats you pick.

## `onlyNewItems` (type: `boolean`):

Remember the rows output by this run and skip them in later runs with the same memory name: schedule it after a scraper and get only rows you have not seen before. Already-seen rows are free. Uses the dedupe fields as the identity (whole row if empty).

## `memoryName` (type: `string`):

Separate memories for separate pipelines (e.g. "shop-a-products"). Lowercase letters, digits and dashes. Stored in a named key-value store in your account (merge-dedupe-memory-<name>); delete it to start over.

## `compareDatasetIds` (type: `array`):

Output only rows that are NOT in these datasets, e.g. the previous run of your scraper: today's run minus yesterday's = what is new. Rows are matched by "Deduplicate by fields" (empty = whole row, so changed rows count as new). Skipped rows are free. Picking a dataset gives this actor read access to it only.

## `compareUrls` (type: `array`):

Same as above for files: JSON, JSON Lines, CSV or Google Sheets links of the previous export (e.g. the sheet you append to).

## `maxItems` (type: `integer`):

Stop after this many unique rows. Empty = no limit.

## `inputFormat` (type: `string`):

Auto detects JSON, JSON Lines and CSV/TSV (and the CSV delimiter) from the extension, Content-Type and content. Force a format if detection gets it wrong.

## `addSourceField` (type: `boolean`):

Add a \_source field with the dataset ID or URL each row came from.

## `flattenDataset` (type: `boolean`):

CSV and Excel are always flat (address/city columns). Turn this on to flatten the dataset and JSON outputs the same way.

## `arrayFormat` (type: `string`):

Join: \["a","b"] becomes "a; b" (lists of objects become JSON). Columns: tags/0, tags/1, ... (like Apify's own export). JSON: the array as JSON text.

## `csvDelimiter` (type: `string`):

Delimiter of merged.csv: , (default), ; (Excel in many European locales) or \t (tab).

## Actor input object example

```json
{
  "sourceUrls": [
    "https://raw.githubusercontent.com/datasets/country-list/main/data.csv",
    "https://raw.githubusercontent.com/datasets/country-codes/main/data/country-codes.csv"
  ],
  "dedupeFields": [
    "Code"
  ],
  "dedupeMode": "normalized",
  "keep": "first",
  "renameFields": {
    "ISO3166-1-Alpha-2": "Code",
    "CLDR display name": "Name"
  },
  "fields": [
    "Code",
    "Name"
  ],
  "outputFormats": [
    "dataset",
    "csv",
    "xlsx"
  ],
  "onlyNewItems": false,
  "inputFormat": "auto",
  "addSourceField": false,
  "flattenDataset": false,
  "arrayFormat": "join",
  "csvDelimiter": ","
}
```

# Actor output Schema

## `results` (type: `string`):

The merged, deduplicated rows (when "Dataset" is among the output formats).

## `csv` (type: `string`):

merged.csv: the result as one CSV file (when CSV is selected).

## `xlsx` (type: `string`):

merged.xlsx: the result as an Excel workbook (when XLSX is selected).

## `json` (type: `string`):

merged.json: the result as one JSON array (when JSON is selected).

## `jsonl` (type: `string`):

merged.jsonl: one JSON object per line (when JSONL is selected).

## `summary` (type: `string`):

Rows read, duplicates removed and errors per source, columns, and file links.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "sourceUrls": [
        "https://raw.githubusercontent.com/datasets/country-list/main/data.csv",
        "https://raw.githubusercontent.com/datasets/country-codes/main/data/country-codes.csv"
    ],
    "dedupeFields": [
        "Code"
    ],
    "renameFields": {
        "ISO3166-1-Alpha-2": "Code",
        "CLDR display name": "Name"
    },
    "fields": [
        "Code",
        "Name"
    ],
    "outputFormats": [
        "dataset",
        "csv",
        "xlsx"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("4b47/merge-dedupe-datasets").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "sourceUrls": [
        "https://raw.githubusercontent.com/datasets/country-list/main/data.csv",
        "https://raw.githubusercontent.com/datasets/country-codes/main/data/country-codes.csv",
    ],
    "dedupeFields": ["Code"],
    "renameFields": {
        "ISO3166-1-Alpha-2": "Code",
        "CLDR display name": "Name",
    },
    "fields": [
        "Code",
        "Name",
    ],
    "outputFormats": [
        "dataset",
        "csv",
        "xlsx",
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("4b47/merge-dedupe-datasets").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "sourceUrls": [
    "https://raw.githubusercontent.com/datasets/country-list/main/data.csv",
    "https://raw.githubusercontent.com/datasets/country-codes/main/data/country-codes.csv"
  ],
  "dedupeFields": [
    "Code"
  ],
  "renameFields": {
    "ISO3166-1-Alpha-2": "Code",
    "CLDR display name": "Name"
  },
  "fields": [
    "Code",
    "Name"
  ],
  "outputFormats": [
    "dataset",
    "csv",
    "xlsx"
  ]
}' |
apify call 4b47/merge-dedupe-datasets --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,4b47/merge-dedupe-datasets"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/GvzbcpSMftY4UwEaJ/builds/gCOJ7e6AEN2x4fqBQ/openapi.json
