# Dataset Merge, Dedupe & Transform - CSV, JSON, XLSX (`rinveta/dataset-merge-dedupe`) Actor

Merge Apify datasets, CSV and JSON files, remove duplicates by chosen fields, filter and rename columns, keep only new items, export CSV or XLSX.

- **URL**: https://apify.com/rinveta/dataset-merge-dedupe.md
- **Developed by:** [Rinveta](https://apify.com/rinveta) (community)
- **Categories:** Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$0.50 / 1,000 items output

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/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

## Dataset Merge, Dedupe & Transform – CSV, JSON, XLSX

**Combine any number of Apify datasets, CSV files and JSON files into one clean dataset.** Remove duplicates by the fields you choose, filter rows, pick and rename columns, and – the part most tools skip – **return only the items you have not seen in a previous run**. Export the result as dataset, CSV or Excel (XLSX).

No browser, no scraping: it only reads the datasets and file URLs **you provide**. Pay only for items that end up in the output.

### What can you do with it?

- **Merge scraper results** from several runs or several Actors into a single dataset.
- **Deduplicate by key** (`url`, `email`, `sku`, `address.city` + `name`…), case- and whitespace-insensitive, or compare whole items.
- **Keep the best duplicate**: first seen, last seen, or the one with the most filled-in fields.
- **Monitor for new items on a schedule**: "only new items" mode remembers what was already delivered (state lives in a named key-value store in *your* account).
- **Filter** (`eq`, `contains`, `gte`, `regex`, `in`, `exists`…), **select columns**, **rename columns**, flatten nested objects, sort.
- **Export CSV and XLSX** next to the dataset, ready for spreadsheets and BI tools.

### Use cases

**1. Scraper → dedupe → only-new (the daily leads / price-drop / new-listing feed).** Run any scraper on a schedule, then run this Actor on the scraper's dataset with `onlyNewItems: true`. Every run delivers only the items you have never received before, so downstream steps (spreadsheet, CRM, email, Slack, webhook) see no repeats. Chain it with an Apify Schedule or an integration that starts this Actor when the scraper run succeeds, and use `datasetIds` with the scraper's default dataset ID.

**2. Merge several scraper runs into one clean dataset.** Same Actor run for several cities, keywords or days? List all the datasets in `datasetIds`, dedupe on `url` (or `sku`, `email`, `id`) and keep the most complete record.

**3. CSV to XLSX converter with cleanup.** Point `sourceUrls` at one or more CSV/TSV/JSON files, drop duplicate rows, rename columns, and download a ready-to-open `OUTPUT.xlsx` (and `OUTPUT.csv`) from the key-value store.

**4. Clean a product or lead list before import.** Filter out rows you do not need, keep only the columns your CRM or shop expects, and export one file.

**5. Compare today with yesterday.** Run with `updateState: false` as a dry run to see what would be new, without changing the saved state.

### Features at a glance

| Feature | This Actor |
|---|---|
| Merge several Apify datasets | ✅ |
| Merge CSV / TSV / JSON / JSON Lines by URL (auto-detected) | ✅ |
| Dedupe by chosen fields, dot-notation for nested fields | ✅ |
| Case / whitespace-insensitive matching | ✅ (on by default, switchable) |
| Keep first / last / most complete duplicate | ✅ |
| Only new items between runs (persistent state) | ✅ |
| Filters (12 operators, all/any) | ✅ |
| Select, order and rename columns, flatten, sort | ✅ |
| Source tracking column | ✅ |
| CSV and XLSX export | ✅ |
| Per-source report (read / filtered / duplicates / errors) | ✅ |
| Pricing | Pay per output item |

Typical single-purpose tools cover one or two of these rows (for example dedupe only, or merge only). This Actor is meant to be the one step between your scrapers and your spreadsheet, CRM or alerting.

### Input

| Field | Description |
|---|---|
| `datasetIds` | Dataset IDs or names to merge (order matters for "keep first"). |
| `sourceUrls` | Public CSV / TSV / JSON / JSONL URLs. Format detected automatically; `jsonPath` for nested lists, `csvDelimiter` to force a delimiter. |
| `dedupeFields` | Fields that define a duplicate. Empty = whole item. |
| `keepStrategy` | `first`, `last`, `mostComplete`. |
| `onlyNewItems`, `stateKey`, `updateState` | Return only never-seen items; separate memory per `stateKey`; `updateState: false` = dry run. |
| `filters`, `filterMode` | List of `{field, op, value}`; `all` or `any`. |
| `includeFields`, `excludeFields`, `renameFields`, `flattenNested`, `trimStrings`, `sortBy`, `sortOrder` | Reshape the output. |
| `addSourceField` | Adds `_source` and `_sourceIndex`. |
| `exportFormats` | `csv`, `xlsx` → `OUTPUT.csv` / `OUTPUT.xlsx` in the key-value store. |
| `maxItems`, `maxItemsPerSource`, `maxFileSizeMB` | Safety limits. |

Order of operations: read → flatten/trim → filter → dedupe → "only new" check → sort → select/rename → output. Dedupe and filters use the **original** field names; renaming happens last.

Example – merge two files and keep one row per symbol:

```json
{
  "sourceUrls": [
    { "url": "https://raw.githubusercontent.com/datasets/s-and-p-500-companies/main/data/constituents.csv" },
    { "url": "https://raw.githubusercontent.com/datasets/nasdaq-listings/main/data/nasdaq-listed.csv" }
  ],
  "dedupeFields": ["Symbol"],
  "addSourceField": true,
  "exportFormats": ["csv", "xlsx"]
}
```

Example – daily "what's new" feed from a scraper's dataset:

```json
{ "datasetIds": ["my-scraper-results"], "dedupeFields": ["url"], "onlyNewItems": true, "stateKey": "daily-leads" }
```

### Output

One dataset item per kept row (your fields, in your column order). The key-value store `OUTPUT` record has the run report:

```json
{ "read": 6121, "filteredOut": 0, "duplicatesRemoved": 158, "alreadySeen": 0, "output": 5963,
  "sources": [ { "source": "https://…/constituents.csv", "read": 503, "filteredOut": 0, "duplicates": 0, "error": null } ] }
```

A source that fails (404, bad file) is reported and skipped; the run continues with the others.

### Pricing

Pay per event: **$0.0005 per output item** (event `item-output`) – 10,000 clean items cost $5. Items that are filtered out, duplicates and already-seen items are **free**. Platform usage is included for normal-sized runs.

### FAQ

**How do I remove duplicates from an Apify dataset?** Put the dataset ID in `datasetIds`, list the fields that identify a duplicate in `dedupeFields` (for example `url`), choose `keepStrategy` and run. The result is a new dataset; your original dataset is not modified.

**How do I get only new items from a scheduled scraper?** Set `onlyNewItems: true` and a fixed `stateKey`. The first run returns everything and remembers it; the next runs return only unseen items. Use a different `stateKey` per feed.

**Can I merge datasets from different Actors?** Yes. Items do not need the same fields; use `renameFields` to align column names (for example `link` → `url`), then dedupe on the common field.

**How do I convert CSV to XLSX?** Provide the CSV URL in `sourceUrls` and set `exportFormats` to `["xlsx"]`. Download `OUTPUT.xlsx` from the run's key-value store.

**Is the "seen" state private?** Yes, it is kept in a named key-value store in your own Apify account.

**What happens if one source fails?** It is reported in the run report (`sources[].error`) and skipped; the other sources are processed.

**What am I charged for?** Only the items in the final output ($0.0005 each). Filtered-out rows, duplicates and already-seen items are free.

### Tips and limits

- Memory grows with the number of unique items (all kept rows are held in memory to dedupe). Around 100,000 average-size items run comfortably in 1–2 GB; raise the Actor memory for millions.
- XLSX is limited by Excel to about one million rows; CSV and the dataset have no such limit.
- "Only new items" state is keyed on the dedupe key. If you change `dedupeFields`, use a new `stateKey`.
- Items removed by filters are not remembered: they count as new if you later relax the filters.
- URLs must be public http(s); private/internal addresses are blocked.
- Uses only data you provide; no personal-data collection is performed by this Actor. You are responsible for the lawful use of the data you process.

### Related Actors

More Actors by Rinveta for data pipelines:

- [Image Compressor & Converter](https://apify.com/rinveta/image-converter): batch conversion and compression of images to WebP, AVIF, JPEG or PNG.
- [PDF to Text & Markdown for RAG](https://apify.com/rinveta/pdf-to-markdown): per-page text, Markdown and page-cited chunks from PDFs.

**Related searches:** merge datasets, combine datasets, dedupe dataset, remove duplicates, deduplicate JSON, only new items, incremental scraping, csv to xlsx, csv merge, json to csv, data cleaning.

# Actor input Schema

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

Datasets to merge (for example the default dataset of other Actor runs). Order is kept: with 'keep first' the earliest source wins.

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

Public links to CSV, TSV, JSON (array), or JSON Lines files. Format is detected automatically. Only the URLs you list are downloaded.

## `jsonPath` (type: `string`):

For JSON files whose items are nested, e.g. 'data.results'. Empty = auto-detect.

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

Leave empty to auto-detect among , ; tab |.

## `csvInferTypes` (type: `boolean`):

Turn '42' into a number and 'true' into a boolean. Values with leading zeros (e.g. '007') stay text. Empty cells become null.

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

Items with the same values in ALL these fields are duplicates. Use dot notation for nested fields (e.g. 'address.city'). Empty list = compare whole items.

## `dedupeTrim` (type: `boolean`):

Remove leading and trailing spaces from the dedupe fields before comparing them.

## `dedupeIgnoreCase` (type: `boolean`):

Treat 'ABC' and 'abc' as the same value when looking for duplicates.

## `keepItemsWithEmptyKey` (type: `boolean`):

On: such items are never treated as duplicates of each other. Off: they all collapse into one.

## `keepStrategy` (type: `string`):

When duplicates are found: keep the first one seen, the last one seen, or the one with the most non-empty fields.

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

Remembers the dedupe keys of everything already output (stored in a named key-value store in YOUR account) and returns only new ones. Perfect for scheduled monitoring.

## `stateKey` (type: `string`):

Separate memory per use case. Use different names for different jobs.

## `updateState` (type: `boolean`):

Turn off for a dry run that does not change the stored memory.

## `filters` (type: `array`):

Array of {"field":"price","op":"gte","value":10}. Operators: eq, neq, contains, notContains, startsWith, gt, gte, lt, lte, regex, in, exists, notExists.

## `filterMode` (type: `string`):

With several filters: 'all' keeps items that match every filter, 'any' keeps items that match at least one.

## `includeFields` (type: `array`):

Output column order. Empty = keep all fields.

## `excludeFields` (type: `array`):

Fields to remove from every output item. Applied after the filters.

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

{"oldName":"newName"}. Applied after filtering and deduping, so use the original names above.

## `flattenNested` (type: `boolean`):

{address:{city:'X'}} becomes 'address.city'. Recommended for CSV/XLSX.

## `trimStrings` (type: `boolean`):

Remove leading and trailing spaces from all text values in each item.

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

Adds \_source and \_sourceIndex so you can see where each kept item came from.

## `sortBy` (type: `string`):

Field name used to sort the output. Leave empty to keep the input order.

## `sortOrder` (type: `string`):

Ascending or descending order, used only when 'Sort by field' is set.

## `exportFormats` (type: `array`):

Also write OUTPUT.csv and/or OUTPUT.xlsx to the run's key-value store.

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

Stop after this many output items. 0 means no limit. Only the items returned (and charged) count.

## `maxItemsPerSource` (type: `integer`):

Read at most this many items from each dataset or file. 0 reads everything.

## `maxFileSizeMB` (type: `integer`):

Skip any URL source larger than this size, to protect memory and compute cost.

## Actor input object example

```json
{
  "sourceUrls": [
    {
      "url": "https://raw.githubusercontent.com/datasets/s-and-p-500-companies/main/data/constituents.csv"
    }
  ],
  "csvInferTypes": true,
  "dedupeFields": [
    "Symbol"
  ],
  "dedupeTrim": true,
  "dedupeIgnoreCase": true,
  "keepItemsWithEmptyKey": true,
  "keepStrategy": "first",
  "onlyNewItems": false,
  "stateKey": "default",
  "updateState": true,
  "filters": [],
  "filterMode": "all",
  "renameFields": {},
  "flattenNested": false,
  "trimStrings": false,
  "addSourceField": false,
  "sortOrder": "asc",
  "exportFormats": [],
  "maxItems": 0,
  "maxItemsPerSource": 0,
  "maxFileSizeMB": 100
}
```

# Actor output Schema

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

Merged, deduplicated and transformed items.

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

Counts per source: read, filtered out, duplicates, already seen, output; export links.

## `files` (type: `string`):

OUTPUT.csv and OUTPUT.xlsx when export formats are selected.

# 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": [
        {
            "url": "https://raw.githubusercontent.com/datasets/s-and-p-500-companies/main/data/constituents.csv"
        }
    ],
    "dedupeFields": [
        "Symbol"
    ],
    "filters": [],
    "renameFields": {}
};

// Run the Actor and wait for it to finish
const run = await client.actor("rinveta/dataset-merge-dedupe").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": [{ "url": "https://raw.githubusercontent.com/datasets/s-and-p-500-companies/main/data/constituents.csv" }],
    "dedupeFields": ["Symbol"],
    "filters": [],
    "renameFields": {},
}

# Run the Actor and wait for it to finish
run = client.actor("rinveta/dataset-merge-dedupe").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": [
    {
      "url": "https://raw.githubusercontent.com/datasets/s-and-p-500-companies/main/data/constituents.csv"
    }
  ],
  "dedupeFields": [
    "Symbol"
  ],
  "filters": [],
  "renameFields": {}
}' |
apify call rinveta/dataset-merge-dedupe --silent --output-dataset

```

## MCP server setup

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

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/EMEi33wDtBT7cVi7L/builds/S8wy5l8CCgEMPIkAs/openapi.json
