# Dataset Sampler: random, stratified & seeded rows (`ucchiii/dataset-sampler`) Actor

Takes a sample of an Apify dataset or a CSV / JSON / NDJSON file: random N rows or percent, every k-th row, first or last N, or a fixed number per group of a column. Same seed gives the same sample. Handles huge inputs row by row. Empty input = free demo.

- **URL**: https://apify.com/ucchiii/dataset-sampler.md
- **Developed by:** [Actor Factory](https://apify.com/ucchiii) (community)
- **Categories:** Developer tools, Automation, Integrations
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.14 / 1,000 sampled rows

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

**Take a random, systematic or stratified sample of a dataset, CSV or JSON file**

**Gives you a small, fair set of rows out of a big table, and the same set again whenever you want it.** For anyone who cannot or should not run something on every row: the data engineer who wants a **spot check before an expensive enrichment run**, the ML engineer who needs a **labelled test set** drawn evenly from every class, the analyst who wants a **preview of a huge scrape** without opening a million rows, the team that needs an **A/B split with a fixed seed** that can be audited later. Pick a method, press Start, and download the sample as CSV, JSON or Excel from the dataset. No code, no spreadsheet.

**Try it free: leave all inputs empty and press Start** (the demo is not charged and its rows carry `_demo: true`).
**$0.20 per 1,000 output rows**, charged per row ($0.0002 a row). A sample of 500 rows costs $0.10. The $5 monthly free credit covers about 25,000 sampled rows. You pay only for the rows you get back, and reading the input is free, so sampling 500 rows out of 2 million costs the same as sampling 500 out of 5,000. Failed runs, runs with no output rows and the demo are free. No scraping, no API keys.

### Sample

Input: a dataset of 60 orders (30 `retail`, 18 `wholesale`, 12 `online`), **Method** `stratified`, **Stratify by column** `segment`, **Rows per group** `2`, **Seed** `smoke`, **Add the group** on.

| order_id | segment | country | total_usd | \_stratum |
|---|---|---|---|---|
| 1015 | retail | JP | 25.5 | retail |
| 1027 | retail | JP | 19.5 | retail |
| 1037 | wholesale | DE | 29.5 | wholesale |
| 1042 | wholesale | IN | 34.5 | wholesale |
| 1056 | online | US | 12.5 | online |
| 1059 | online | JP | 33.5 | online |

Two rows from every segment, although `online` is only a fifth of the data. Rows come back with their original fields, in the order they had in the input. Nothing is changed or reformatted. The extra columns `_stratum` and `_sampleIndex` are only added when you ask for them.

### What it does

- **Random N rows**: exactly N rows, every row equally likely. It reads the input once and keeps only N rows in memory (reservoir sampling), so a dataset of millions of rows is fine.
- **Random percentage**: exactly P% of the rows (rounded, at least one). The Actor first counts the rows (reading is free), then picks them, so you get the exact number, not "about".
- **Every k-th row (systematic)**: row 1, 101, 201 ... for k = 100. Choose the starting row, or let the seed choose a random start so a repeating pattern in the data cannot line up with your step.
- **First N and last N rows**: a plain head or tail. First N stops reading as soon as it has N rows.
- **Stratified by a column**: a fixed number of rows (or a percentage) from every value of a column, for example 50 reviews from each star rating or 10% of every country. Small groups are not drowned out: a group with fewer rows than you ask for is returned completely, and a percentage always keeps at least one row per group.
- **Seed for repeatable results**: the same seed on the same input and settings gives exactly the same sample. The seed can be a number or any text. If you leave it empty, a new seed is chosen and written to the run summary, so even an unplanned draw can be reproduced afterwards.
- **Dedupe key**: list columns such as `email` or `url`, and every combination can only be drawn once (the first row of each stays). Dedupe happens before sampling, so duplicates do not make a value more likely to be picked.
- **Two kinds of input**: Apify datasets (resource picker, read permission only) and public CSV / TSV / JSON / NDJSON file URLs, mixed freely. Encoding (UTF-8, Shift JIS, Windows-1252) and delimiter (comma, semicolon, tab, pipe) are detected.
- **Optional extra columns**: `_sampleIndex` is the position of the row in the input, so you can find it again in the source. `_stratum` is the group the row came from.
- **Nested fields**: group or dedupe by a nested value with dots, for example `owner.type`.

### Input example

```json
{
  "fileUrls": ["https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"],
  "method": "random_n",
  "sampleSize": 20,
  "seed": "42"
}
```

A labelled test set with 100 rows from every class of an Apify dataset, with the class and the position in the source added:
`{"datasetIds": ["<id>"], "method": "stratified", "stratifyBy": "label", "perGroupSize": 100, "seed": "testset-v1", "addStratum": true, "addSampleIndex": true}`.
A 5% preview of a big scrape, one row per URL:
`{"datasetIds": ["<id>"], "method": "random_percent", "samplePercent": 5, "dedupeFields": ["url"]}`.
An A/B split you can audit: `{"datasetIds": ["<id>"], "method": "random_percent", "samplePercent": 50, "seed": "experiment-7", "addSampleIndex": true}` gives group A. Run it again later with the same seed and you get the same group A; group B is every row whose `_sampleIndex` is not in it.

### Output

- **Dataset**: the sampled rows in input order. Download as CSV, JSON, Excel and more from the Console.
- **STATS** record (key-value store): `method`, `seed` (and `seedGenerated`), `inputRows` (rows read), `eligibleRows` (after dedupe), `outputRows`, `chargedRows`, `duplicatesRemoved`, and for stratified sampling the input and output rows of every group in `strata`.

### Rules worth knowing

- **Same seed, same sample** holds when the rows and their order are the same. A dataset that has new or reordered rows, or a file that changed, gives a different sample for the same seed.
- **Rows are counted from 1 in the order they are read**: datasets first (in the order you list them), then the files. Rows removed by dedupe still count for `_sampleIndex`, so it always points at the row in the source.
- **Stratified groups** are the exact values of the column, with surrounding spaces ignored (`US` and `us` are two groups). Rows with a missing or empty value form their own group called `(empty)`.
- **Random percentage and stratified percent** read the input twice. If the source changes between the two reads, the result can differ slightly from the exact count.
- **First N** reports the rows it read, not the size of the whole input (`inputRowsComplete` is false in STATS).
- **A sample larger than the input** returns all rows, and the summary says so.
- **Maximum cost per run**: for First N, Last N and Random N the sample size is reduced to what the budget covers (still a valid sample, just smaller). For the other methods the run stops before writing anything, without charging, and tells you the number of rows you would have got, because cutting a sample short would make it biased.

### Limits (cannot be raised by input)

- Samples of up to 1,000,000 rows, and up to 100,000 different groups in a stratified run. The sample, not the input, has to fit in memory: a sample of a few thousand rows runs in the smallest memory setting. Very large samples (hundreds of thousands of rows) need more memory in the run options.
- 20 datasets and files per run; 100 MB per file (a JSON array: 50 MB, because it has to be read whole; use NDJSON, one object per line, for bigger files).
- Dedupe keeps a 16-byte fingerprint of every distinct key in memory, so dedupe on tens of millions of distinct keys needs a lot of memory.
- Source URLs must be public `http` or `https` links. Addresses on internal networks (localhost, private ranges, cloud metadata) are blocked, also after redirects. Excel files are not read (save them as CSV first).

### Pricing

Pay per event: **$0.20 per 1,000 output rows** (event `row`, $0.0002 per sampled row). Reading input rows is free. Nothing is charged when the run fails or produces no rows. On the Apify Free plan, the $5 of monthly platform credit covers about **25,000 sampled rows** a month.

### Use cases

- Spot-check the output of a scraper or a data pipeline on a few hundred rows before paying for an enrichment, geocoding or LLM run on all of them
- Build a labelled test or evaluation set for a classifier or an LLM prompt, with the same number of examples per class
- Look at a representative preview of a huge dataset in a spreadsheet
- Split users or records into A/B groups in a way you can reproduce and audit later
- Take every 100th row of a time-ordered log for a quick trend check
- Keep a small, stable fixture of production data for tests

### Use it from the API or an AI agent

Start the Actor over the Apify API and read the sample in one call:

```bash
curl -X POST "https://api.apify.com/v2/acts/ucchiii~dataset-sampler/run-sync-get-dataset-items?token=<YOUR_API_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"datasetIds": ["<dataset id>"], "method": "random_n", "sampleSize": 200, "seed": "audit-1"}'
```

The response is the array of sampled rows. Use `/runs` and the key-value store record `STATS` if you also want the seed and the per-group counts. The Actor is also available as a tool to AI agents through the [Apify MCP server](https://mcp.apify.com) (add `ucchiii/dataset-sampler` to its tools): an agent can pass the input above and gets the sampled rows back, with the seed in `STATS` so the same sample can be requested again.

### FAQ

**Does it change my source dataset?** No. It only reads it and writes a new dataset.
**Does it change my values?** No. Rows are returned as they were, in their original order. Only `_sampleIndex` and `_stratum` are added, and only when you turn them on.
**Why do I get the same rows every time?** You gave a seed. Leave the seed empty for a different sample each run.
**How do I get a different sample from the same data?** Change the seed (any text), or leave it empty.
**Is a random sample random enough for a test set?** Yes for a plain uniform sample. If one class is rare, use the stratified method so the rare class is represented.
**Can I get the rows in random order instead of input order?** The sample keeps the input order. Sort it by a random key in your next step if you need it shuffled.
**What if I want the rows that were not sampled?** Keep `_sampleIndex` and filter the source by it, or run a second sample with a different seed and dedupe on an ID.
**Can I sample a file bigger than memory?** Yes for CSV, TSV and NDJSON (up to 100 MB each): rows are read one at a time. A JSON array is read whole, so it is limited to 50 MB.

If this Actor saved you time, a rating on the Store helps others find it.

### More tools from the same developer

- [Dataset Splitter](https://apify.com/ucchiii/dataset-splitter) — split a dataset or CSV/JSON file into parts by rows, parts, column value or size, or take a random sample
- [Filter CSV, JSON or Dataset Rows by Condition](https://apify.com/ucchiii/filter-rows) — keep only the rows of a CSV, JSON file or dataset that match simple conditions like country = US or price > 100
- [Remove Duplicates](https://apify.com/ucchiii/dataset-dedup-merge) — merge Apify datasets and remove duplicates by the fields you choose
- [Dataset Transform](https://apify.com/ucchiii/dataset-transform) — flatten, filter, rename and convert any Apify dataset, export CSV / JSON / JSONL with a link

# Actor input Schema

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

Datasets to sample from (the 'defaultDatasetId' of a finished run). You can paste a dataset URL from Apify Console too. Several datasets and files are read in the order given and sampled together as one table. Up to 20 in total. Leave this and 'File URLs' empty to run a free demo on a built-in sample (not charged).

## `fileUrls` (type: `array`):

Public http(s) links to CSV, TSV, JSON or NDJSON files (up to 100 MB each; a JSON array up to 50 MB, use NDJSON for bigger files). The encoding (UTF-8, Shift JIS, Windows-1252) and the delimiter are detected. Links to internal networks are blocked.

## `method` (type: `string`):

How to pick the rows. Random N uses reservoir sampling and reads the input once. Random percentage and stratified percent read the input twice (first to count the rows, reading is free) so the number of rows is exact. First N stops reading after N rows. Default: Random N rows.

## `sampleSize` (type: `integer`):

Number of rows for the methods Random N, First N and Last N. If the input has fewer rows, all of them are returned. Default: 100.

## `samplePercent` (type: `number`):

For the method Random percentage: the share of the rows to return, for example 5 for 5%. The result has the rounded number of rows (at least 1), not 'about' that many. Default: 10.

## `step` (type: `integer`):

For the method Every k-th row: return one row out of every k, for example 100 returns rows 1, 101, 201 ... (rows counted after dedupe). Default: 10.

## `startAt` (type: `integer`):

For the method Every k-th row: the row number (starting at 1) of the first row returned. Ignored when 'Random start' is on. Default: 1.

## `randomStart` (type: `boolean`):

For the method Every k-th row: begin at a random row among the first k, chosen from the seed. This avoids always picking the same position in a repeating pattern. Default: off.

## `stratifyBy` (type: `string`):

For the method Stratified: the column whose values form the groups, for example country or category. Nested fields use dots (owner.type). Rows with an empty value form their own group named '(empty)'. Required for stratified sampling.

## `perGroupSize` (type: `integer`):

For the method Stratified: number of random rows from every group. A smaller group is returned completely. Set this or 'Percent per group', not both. 0 = not used. Default: 0.

## `perGroupPercent` (type: `number`):

For the method Stratified: share of every group to return, for example 10 for 10% of each group (at least 1 row per group, so rare groups stay in the sample). Set this or 'Rows per group', not both. 0 = not used. Default: 0.

## `seed` (type: `string`):

Any text or number. The same seed on the same input (same rows in the same order) and the same settings gives exactly the same sample, so you can repeat a split or an audit. Empty = a new random seed each run; it is written to the run summary (record STATS) so you can reproduce the run later.

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

Column names. Before sampling, a row whose values in these columns equal those of an earlier row is dropped, so every combination can be drawn only once (the first row of each stays). Two empty values are equal. Only a short fingerprint of each key is kept in memory. Empty list = no dedupe.

## `addSampleIndex` (type: `boolean`):

Add a field '\_sampleIndex' to every output row: its position in the input (1 = first row read, counted across all sources before dedupe). Useful to find the row in the source again. Default: off.

## `addStratum` (type: `boolean`):

Add a field '\_stratum' to every output row: the group value the row was sampled from. Only for the method Stratified. Default: off.

## Actor input object example

```json
{
  "fileUrls": [
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
  ],
  "method": "random_n",
  "sampleSize": 100,
  "samplePercent": 10,
  "step": 10,
  "startAt": 1,
  "randomStart": false,
  "perGroupSize": 0,
  "perGroupPercent": 0,
  "addSampleIndex": false,
  "addStratum": false
}
```

# Actor output Schema

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

The sampled rows with their original fields, in input order. Download as CSV, JSON, Excel and more.

## `stats` (type: `string`):

Record STATS: method, seed (also when it was generated for you), rows read, rows written and charged, duplicates removed and, for stratified sampling, input and output rows per group.

# 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 = {
    "fileUrls": [
        "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/dataset-sampler").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 = { "fileUrls": ["https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"] }

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/dataset-sampler").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 '{
  "fileUrls": [
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
  ]
}' |
apify call ucchiii/dataset-sampler --silent --output-dataset

```

## MCP server setup

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

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/CDw7pUBwCT1E6YDwD/builds/i5jFapQi81ZnN9xz2/openapi.json
