# CSV Data Cleaner (`dr.skywalker/csv-data-cleaner`) Actor

Upload a CSV file and get back a clean version: duplicate rows removed, whitespace trimmed, null-like values normalized, empty rows dropped. Includes a stats report of everything that was fixed.

- **URL**: https://apify.com/dr.skywalker/csv-data-cleaner.md
- **Developed by:** [Luqin Wang](https://apify.com/dr.skywalker) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $50.00 / 1,000 csv file cleaneds

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

## CSV Data Cleaner

Upload a messy CSV and get back a clean one — duplicates removed, whitespace trimmed,
null-like values (`null`, `n/a`, `none`, `-`, …) normalized to empty cells, and empty
rows dropped. You also get a `STATS.json` report showing exactly what changed.

### Input

| Field | Description |
|---|---|
| CSV file to clean | Upload a `.csv` file from your computer |
| Or: CSV file URL | Public URL of a CSV file |
| Or: paste CSV text | Paste raw CSV content directly |
| Delimiter | `,` `;` tab or `|` (default: comma) |
| Remove duplicate rows | On by default |
| Trim whitespace | On by default |
| Normalize null-like values | On by default |
| Remove empty rows | On by default |

Only one source is needed; priority is uploaded file → URL → pasted text.

### Output

- **Dataset**: one item per cleaned row, with a stable `recordId`. Duplicate
  headers receive deterministic `__2`, `__3`, … suffixes and cells beyond the
  source header use `extraColumn_1`, `extraColumn_2`, … so no cell is lost.
- **Key-value store `CLEANED`**: the cleaned CSV file (`text/csv`)
- **Key-value store `STATS`**: JSON report, e.g.

```json
{
  "totalInputRows": 1000,
  "chargedInputRows": 1000,
  "outputRows": 972,
  "duplicatesRemoved": 21,
  "nullsNormalized": 45,
  "emptyRowsRemoved": 7,
  "columns": 8,
  "sourceColumnNames": ["id", "name", "email", ...],
  "datasetFieldNames": ["id", "name", "email", ...],
  "delimiterUsed": ","
}
```

### Pricing (pay-per-event)

- **$0.05** per CSV file cleaned
- **$0.0001** per input row processed

Charges are journaled before paid work, and each intent links to a partitioned
source snapshot. If the normal post-charge journal update fails, an immutable
acceptance receipt retains the accepted count and snapshot link. If a charge is
only partly accepted, only its charged prefix is delivered and the raw suffix
is preserved in byte-bounded `RECOVERY-*` records. Recovery carries actual
fitted cleaned values as well as raw rows. Terminal dataset or key-value-store
failures also create a `PRESERVATION-REPORT` for record-ID reconciliation; a
partial preservation report lists every successful key and record ID rather
than claiming all-or-nothing success.

Runs admit at most 8 MiB of CSV input, 100,000 parsed rows, and 500,000
conservatively estimated CSV cells. Larger inputs fail before parser allocation,
cleaning, or row billing instead of risking unbounded memory use.

### Run via API

```bash
curl -H "Authorization: Bearer $APIFY_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{"csvUrl": "https://example.com/messy.csv"}' \
     "https://api.apify.com/v2/acts/<username>~csv-data-cleaner/runs?waitForFinish=60"
```

### Local development

```bash
mkdir -p storage/key_value_stores/default
cp test/INPUT.json storage/key_value_stores/default/INPUT.json
APIFY_LOCAL_STORAGE_DIR=./storage python3 -m src.main
## results: storage/datasets/default/ + storage/key_value_stores/default/CLEANED + STATS
```

# Actor input Schema

## `csvFile` (type: `string`):

Upload a .csv file from your computer. It is stored in the run's key-value store and read by the actor.

## `csvText` (type: `string`):

Paste raw CSV content. Used only when no file or URL is provided.

## `csvUrl` (type: `string`):

Public URL of a CSV file to clean. Used when no uploaded file is provided and takes precedence over pasted text.

## `dedupe` (type: `boolean`):

Drop rows that are exact duplicates of an earlier row.

## `delimiter` (type: `string`):

Field delimiter used in the CSV file.

## `normalizeNulls` (type: `boolean`):

Convert values like 'null', 'none', 'n/a', 'NA', '-', '--', 'nil' to empty cells.

## `removeEmptyRows` (type: `boolean`):

Drop rows where every cell is empty after trimming.

## `trimWhitespace` (type: `boolean`):

Remove leading/trailing whitespace from every cell.

## Actor input object example

```json
{
  "csvUrl": "https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv",
  "dedupe": true,
  "delimiter": ",",
  "normalizeNulls": true,
  "removeEmptyRows": true,
  "trimWhitespace": true
}
```

# Actor output Schema

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

Key-value store with the CLEANED.csv file and STATS.json report.

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

Dataset with one item per cleaned CSV row.

# 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 = {
    "csvUrl": "https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
};

// Run the Actor and wait for it to finish
const run = await client.actor("dr.skywalker/csv-data-cleaner").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 = { "csvUrl": "https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv" }

# Run the Actor and wait for it to finish
run = client.actor("dr.skywalker/csv-data-cleaner").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 '{
  "csvUrl": "https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
}' |
apify call dr.skywalker/csv-data-cleaner --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,dr.skywalker/csv-data-cleaner"
        }
    }
}
```

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/1gMnzqZ7mezLmBYmI/builds/dLBwNZyHeiuULb6IC/openapi.json
