# Dataset Pivot Wider: long to wide for CSV & datasets (`ucchiii/dataset-pivot-wider`) Actor

Turns a long table (one row per customer and month) into a wide one (one row per customer, one column per month) for a CSV / JSON file or an Apify dataset. Sum, mean, count, min, max, first or last of the values. Empty input = free demo.

- **URL**: https://apify.com/ucchiii/dataset-pivot-wider.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 output 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/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

**Pivot a long CSV, JSON file or Apify dataset into a wide table**

**Turns "one row per customer and month" into "one row per customer, one column per month".** For anyone who gets data in the long shape and needs the wide one: a scraper dataset with one row per product and day that should become one row per product with a column for every day, a CSV export with one row per region, product and quarter that a report wants as one row per region and product, survey answers stored as question / answer pairs. Name the columns, press Start, and download the wide rows as CSV, JSON or Excel from the dataset (or as one CSV file). It works from the Console form: no code, no spreadsheet pivot table.

**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), and an output row is one row of the wide table. A table with 5,000 customers costs $1.00 however many months it has. The $5 monthly free credit covers about 25,000 output rows. Reading input rows is free. Failed runs, runs with no output rows and the demo are free. No scraping, no API keys.

### Sample

Input rows (a dataset or a CSV file) with **Index columns** `region`, `product`; **Names from** `quarter`; **Values from** `revenue`; **Aggregate** `sum`; **Prefix** `revenue_`; **Fill missing cells with** `0`:

| region | product | quarter | revenue |
|---|---|---|---|
| East | Tools | Q1 | 1,200 |
| East | Tools | Q2 | 1,450 |
| East | Garden | Q1 | 300 |
| East | Garden | Q2 | 420 |
| West | Tools | Q1 | 980 |
| West | Garden | Q1 | 150 |
| West | Garden | Q2 | 210 |
| West | Garden | Q2 | 40 |
| East | Tools | Q3 | 1,610 |
| West | Tools | Q3 | 1,005 |

Output (4 rows, 3 new columns):

| region | product | revenue_Q1 | revenue_Q2 | revenue_Q3 |
|---|---|---|---|---|
| East | Tools | 1200 | 1450 | 1610 |
| East | Garden | 300 | 420 | 0 |
| West | Tools | 980 | 0 | 1005 |
| West | Garden | 150 | 250 | 0 |

West / Garden had two rows for Q2 (210 and 40), which were summed to 250. East / Garden and West / Garden have no Q3, and West / Tools has no Q2, so those cells took the fill value `0` (leave it empty to get null).

### What it does

- **Groups rows by your index columns**: one output row for every distinct combination, in the order the combinations first appear. Empty values count as equal; the number `1` and the text `"1"` are the same value.
- **Makes one new column per distinct value of "Names from"**, in the order the values first appear (stable, not alphabetical). Names are exact text and case-sensitive (`A` and `a` are two columns). Use **Prefix for new columns** to get `revenue_Q1` instead of `Q1`, or to keep numeric names like `2024` readable.
- **Fills the cells from one or more value columns.** With several value columns the new columns are named `<name>_<column>` (`Jan_qty`, `Jan_price`).
- **Seven ways to combine rows that land in the same cell**: `first` (default), `last`, `sum`, `mean`, `count`, `min`, `max`. `first` and `last` keep the value exactly as it was (text stays text, `007` stays `007`) and skip empty values. `sum`, `mean`, `min` and `max` read numbers (also written as `1,200`, `$5` or `12%`), and values that are not numbers are ignored and counted in the run summary. `count` counts the non-empty values.
- **Fills missing cells** (no row for that index and name) with the value you give, or null. A number such as `0` is written as a number when you sum, average, count or take the min / max.
- **Two kinds of input**: Apify datasets (resource picker, read permission only) and public CSV / TSV / JSON / NDJSON file URLs, mixed freely and pivoted together as one table. Encoding (UTF-8, Shift JIS, Windows-1252) and delimiter (comma, semicolon, tab, pipe) are detected.
- **Nested fields**: use dots, for example `owner.id` as an index column.
- **CSV copy**: turn on **Also save a CSV file** to get the wide rows as one file in the key-value store (record `pivoted.csv`, UTF-8 with BOM so Excel opens it correctly).

### Input example

```json
{
  "fileUrls": ["https://raw.githubusercontent.com/mwaskom/seaborn-data/master/flights.csv"],
  "indexColumns": ["year"],
  "namesFrom": "month",
  "valuesFrom": ["passengers"]
}
```

One row per year with a column for each month. A dataset with the average pulse per person and activity at each time point:
`{"datasetIds": ["<id>"], "indexColumns": ["id", "kind"], "namesFrom": "time", "valuesFrom": ["pulse"], "aggregate": "mean", "namePrefix": "pulse_"}`.

### Output

- **Dataset**: the wide rows, index columns first, then the new columns. Download as CSV, JSON, Excel and more from the Console.
- **`pivoted.csv`** (key-value store, only with **Also save a CSV file**).
- **STATS** record (key-value store): `inputRows`, `outputRows`, `chargedRows`, the list of new `columns`, rows read per source in `sources`, `rowsWithoutName`, `valuesNotNumeric` and `notes`.

### Rules worth knowing

- **Rows with an empty "Names from" value are skipped** (there is no column to put them in) and counted in the run summary.
- **A wrong column name stops the run before anything is written or charged.** The error names the missing column and lists the columns that were found. Names are case-sensitive; a column only has to exist in one row.
- **A new column that would have the same name as an index column** gets `_2` added (`k_2`), and the run summary says so.
- **Values keep their type in the output** for `first` and `last`. A CSV file has no types, so its values stay text exactly as written. The numeric aggregates write numbers.
- **`count` of nothing is 0.** A cell with no row at all takes the fill value, not 0, unless you set it so.

### Limits (cannot be raised by input)

- **Up to 50,000 input rows and 10 minutes per run.** A pivot needs every row, so all rows are held in memory. If there are more rows than **Max input rows**, the run stops without pivoting or charging rather than pivoting a partial read, which would give wrong numbers. If the 10-minute limit is hit, the run also stops without writing or charging. Split the data first (for example by a column value).
- **Up to 500 new columns per run** (distinct names times value columns). Over that the run stops with a clear message and nothing is charged: pick a names column with fewer distinct values or filter the rows first.
- 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); 20 index columns and 20 value columns.
- 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 output row). Reading input rows is free. Nothing is charged when the run fails or produces no rows. Set a maximum charge per run: the Actor then writes only the first rows of the result that fit the budget (never past it) and says so in the run summary. If the budget is lower than the price of one row, the run stops at once without charging.
On the Apify Free plan, the $5 of monthly platform credit covers about **25,000 rows** a month.

### Use cases

- Turn a scraper dataset with one row per product and date into one row per product with a column per date
- Reshape a long export (region, product, quarter, revenue) into the wide table a report or import expects
- Count how often each value occurs per customer, one column per value (`count`)
- Average repeated measurements per person and time point
- Prepare a one-row-per-record file for the next Actor in a workflow

### FAQ

**Does it change my source dataset?** No. It only reads it and writes a new dataset.
**Why is a cell empty?** No row had a value for that index and name. Set **Fill missing cells with** (for example `0`).
**Why is my sum a text?** It is not: `sum` always writes numbers. With `first` or `last` the value is copied as it was, so a CSV value stays text.
**Can I do the opposite (wide to long)?** This Actor only goes from long to wide.
**What if there are more than 500 distinct names?** The run stops before writing anything. Filter the rows (for example to the top names) or use another names column.

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

### More tools from the same developer

- [Dataset Explode & Unpivot](https://apify.com/ucchiii/dataset-explode-unpivot) — explode array fields into rows, unpivot wide columns into name/value rows, or pivot back
- [Group By & Aggregate](https://apify.com/ucchiii/dataset-groupby-aggregate) — group dataset or CSV rows by columns and get counts, sums, averages, medians and pivot tables, one row per group
- [Dataset Sort](https://apify.com/ucchiii/dataset-sort) — sort a CSV, JSON file or dataset by one or more columns: numbers, text or dates, natural order, top-N and dedupe
- [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
- [Merge Datasets](https://apify.com/ucchiii/merge-datasets) — combine several datasets or CSV/JSON files into one, with columns aligned

# Actor input Schema

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

Datasets to pivot (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 pivoted 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.

## `indexColumns` (type: `array`):

The columns that identify one output row, for example customer, or region and product. Rows with the same values in all of them are merged into one output row (empty values count as equal). Nested fields use dots (owner.name). Required unless you run the demo.

## `namesFrom` (type: `string`):

The column whose values become the names of the new columns, for example month. Every distinct value makes one new column (two value columns make two each). Rows where this is empty are skipped. Required unless you run the demo.

## `valuesFrom` (type: `array`):

The column or columns whose values fill the new columns, for example revenue. With more than one, the new columns are named <name>\_<column>. Required unless you run the demo.

## `aggregate` (type: `string`):

What goes into a cell when several rows share the same index and name. 'first' and 'last' keep the value as it was (text stays text); empty values are skipped. 'sum', 'mean', 'min' and 'max' read numbers (also '1,200', '$5', '12%') and ignore values that are not numbers. 'count' counts the non-empty values. Default: first.

## `fillMissing` (type: `string`):

The value for a cell when no row has a value for that index and name. Leave it empty to get null. With sum, mean, min, max or count a number such as 0 is written as a number. Default: empty (null).

## `namePrefix` (type: `string`):

Text put in front of every new column name, for example revenue\_ turns Q1 into revenue_Q1. Useful when the names are numbers or could clash with an index column. Default: none.

## `outputCsv` (type: `boolean`):

Besides the dataset, save the wide rows as one CSV file in the key-value store (record 'pivoted.csv', UTF-8 with BOM so Excel opens it correctly). Default: off.

## `maxInputRows` (type: `integer`):

Safety limit on the rows read across all sources. A pivot needs every row, so if there are more rows than this the run stops without pivoting or charging (it never pivots a partial read). Default and cap: 50,000 (a larger value is lowered to 50,000).

## Actor input object example

```json
{
  "fileUrls": [
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/flights.csv"
  ],
  "indexColumns": [
    "year"
  ],
  "namesFrom": "month",
  "valuesFrom": [
    "passengers"
  ],
  "aggregate": "first",
  "outputCsv": false,
  "maxInputRows": 50000
}
```

# Actor output Schema

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

One row per distinct combination of the index columns, with the new columns in order of first appearance. Download as CSV, JSON, Excel and more.

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

The wide rows as one CSV file (UTF-8 with BOM, opens correctly in Excel). Only exists when 'Also save a CSV file' is on.

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

Record STATS: rows read per source, rows written and charged, the new column names, rows skipped for an empty name and values that were not numbers.

# 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/flights.csv"
    ],
    "indexColumns": [
        "year"
    ],
    "namesFrom": "month",
    "valuesFrom": [
        "passengers"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/dataset-pivot-wider").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/flights.csv"],
    "indexColumns": ["year"],
    "namesFrom": "month",
    "valuesFrom": ["passengers"],
}

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/dataset-pivot-wider").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/flights.csv"
  ],
  "indexColumns": [
    "year"
  ],
  "namesFrom": "month",
  "valuesFrom": [
    "passengers"
  ]
}' |
apify call ucchiii/dataset-pivot-wider --silent --output-dataset

```

## MCP server setup

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

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/gic6T0ETIIYqbKMfR/builds/EBS0HPGHNt54eFfTt/openapi.json
