# Group By & Aggregate: Pivot Table for Datasets (`ucchiii/dataset-groupby-aggregate`) Actor

Groups the rows of an Apify dataset or CSV/JSON files by one or more columns and computes count, sum, average, min, max, distinct count, first, last or median per group, with an optional pivot. Empty input runs a free demo.

- **URL**: https://apify.com/ucchiii/dataset-groupby-aggregate.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.49 / 1,000 input 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

**Group the rows of a dataset or CSV by one or more columns and get totals, averages, counts and more for each group, with an optional pivot table.**

You scraped 80,000 product rows and want the average price per brand. You have an order export and want revenue per country and month. You want the top 10 categories by number of items. In a spreadsheet that is a pivot table; in SQL it is a GROUP BY. This Actor does it for **Apify datasets and CSV / TSV / JSON / NDJSON files** from the Console form, with no code and no spreadsheet row limit.

- **Cost:** $0.70 per 1,000 input rows ($0.0007 per row) plus $0.0005 per run for the start. **The $5 monthly free credit covers about 7,000 rows.** The demo, failed runs and rows over your limit are free.
- **Try it free:** clear the file URL field and press **Start**. A built-in sample of 12 orders is grouped by region (not charged, rows carry `_demo: true`).

### What you get

Input: 12 orders (region, product, quarter, amount). Group by `region`, ignore case, aggregations `orders = count`, `revenue = sum of amount`, `avg_order = avg of amount`, `biggest_order = max of amount`, `products = count_distinct of product`, pivot on `quarter` (sum of amount), sorted by revenue, largest first:

| region | orders | revenue | avg_order | biggest_order | products | Q1 | Q2 |
|---|---|---|---|---|---|---|---|
| North | 3 | 604.5 | 201.5 | 267 | 3 | 394.5 | 210 |
| East | 2 | 522 | 261 | 420 | 2 | 420 | 102 |
| West | 4 | 397.4 | 99.35 | 210 | 4 | 257.4 | 140 |
| South | 3 | 346 | 115.33 | 178 | 2 | 178 | 168 |

- One output row per group. Your group-by columns come first, then one column per aggregation (named as you like), then one column per pivot value.
- `north` and `North` fell into one group because spaces were trimmed and case was ignored.

### What it does

- **Group by one or more columns.** Up to 10, nested fields with dots (`address.city`). Leave it empty to get a single row with the totals of the whole table.
- **Nine aggregations.** `count`, `sum`, `avg`, `min`, `max`, `count_distinct`, `first`, `last`, `median`. You name each output column and say which input column it is calculated from. Up to 30 aggregations per run.
- **Simple pivot.** One column's values become output columns (quarters, countries, plans), each cell holding one aggregation, such as the sum of `amount`. Up to 1,000 pivot columns (default 100); more than that stops the run before anything is charged.
- **Sort and limit.** Sort by any output column (numbers sort as numbers, empty values last), then keep the first N groups for a top list.
- **Forgiving values.** Trim spaces (on by default, also full-width spaces) and ignore upper/lower case (off by default). `123`, `123.0` and `"123"` are the same group; `00123` is not `123`. An empty group value is its own group, shown as `null`.
- **Numbers from CSV text.** In CSV files every value is text. `sum`, `avg` and `median` read `"12.5"`, `" 7 "` and `"1,234.50"` as numbers and ignore values that are not numbers (the count is reported in the notes).
- **Several sources at once.** One dataset plus up to 20 files, read as one table.
- **Big tables.** Rows are streamed one by one; only the groups are kept in memory (up to 500,000 groups). `median` and `count_distinct` keep their values per group, so use them on fewer columns for very large inputs.

### How to use

1. **Apify dataset** and/or **File URLs**: the rows to group.
2. **Group by columns**: for example `country`.
3. **Aggregations**: a list of calculations. Each has a `name`, a `field` and a `function`:

```json
{
  "datasetId": "WkzbQMuFYuamGv3YF",
  "groupBy": ["country", "category"],
  "aggregations": [
    {"name": "orders", "function": "count"},
    {"name": "revenue", "field": "amount", "function": "sum"},
    {"name": "avg_price", "field": "price", "function": "avg"},
    {"name": "customers", "field": "email", "function": "count_distinct"}
  ],
  "sortBy": "revenue",
  "sortOrder": "desc",
  "limit": 10
}
```

For a pivot add `"pivotColumn": "month"`, `"pivotField": "amount"` and `"pivotFunction": "sum"`.

### The aggregations

| function | needs `field` | result |
|---|---|---|
| `count` | no | with no field: the number of rows in the group. With a field: the rows where that field is not empty |
| `sum` | yes | total of the numbers (`null` if there is no number) |
| `avg` | yes | average of the numbers |
| `median` | yes | middle number (average of the two middle ones for an even count) |
| `min` / `max` | yes | smallest / largest number; if the values are text, the first / last in alphabetical order |
| `count_distinct` | yes | number of different non-empty values (trimmed; case ignored if you chose so) |
| `first` / `last` | yes | first / last non-empty value in input order |

Empty values (null, empty text, spaces only) are skipped by every function except a field-less `count`.

### Output

- **Dataset**: one row per group, ready to download as CSV, Excel, JSON, XML or HTML. Group-by values are shown as they appear in the first row of the group (trimmed if trimming is on).
- **STATS** record (key-value store): input rows read, number of groups, the output columns, rows charged, and notes (for example values ignored because they were not numbers, or a stop at your limit).

| field | meaning |
|---|---|
| *group-by columns* | the values that define the group |
| *aggregation columns* | one per aggregation, named by you |
| *pivot columns* | one per value of the pivot column |
| `_demo` | `true` on the free demo rows |

### Limits (cannot be raised by input)

- Up to 10 group-by columns, 30 aggregations, 500,000 groups, 20 file URLs and 10,000,000 input rows per run (the default **Max input rows** is 1,000,000)
- Files up to 100 MB each; JSON arrays up to 50 MB (use NDJSON for bigger files). Excel files are not read: save them as CSV first. Public links only (no login); addresses on internal networks are blocked
- A source that cannot be read (wrong dataset ID, HTTP error, broken JSON), a column that no row has (a typo), a pivot with too many values or too many groups stops the run **before anything is written or charged**
- Set a maximum cost per run to cap spend: the run reads as many rows as the limit pays for (after the start fee), stops cleanly (status Succeeded) and says so in the status message and STATS. The result then covers only the rows read.

### Pricing

Pay per event: **$0.0007 per input row** ($0.70 per 1,000 rows) and **$0.0005 per run**. You pay for the rows read, not for the groups written, so a 1,000-row table costs $0.7005 whether it makes 3 groups or 300. The run fee is charged once, only when the run read at least one row and wrote its result, so a very small run still covers its start cost. The header row of a CSV is not counted. Failed runs, invalid input, rows over your limit and the demo are not charged.
Store discounts apply automatically: BRONZE −10%, SILVER −20%, GOLD −30%.
On the Apify Free plan, the $5 of monthly platform credit covers about 7,000 rows in one run.

### FAQ

**Is it the same as a pivot table?** The pivot option gives the same layout for one row field (or several), one column field and one aggregation. For several different aggregations per column, list them under **Aggregations** instead.

**Why is my sum empty (`null`)?** None of the values in that group were numbers. In CSV files check the column for text like `n/a` or currency symbols; the STATS notes tell how many values were ignored.

**Why did I get two groups that look the same?** They differ in case (`North` and `north`) or in a character you cannot see. Turn on **Ignore upper/lower case** and **Trim spaces**.

**Does the limit make the run cheaper?** No. **Limit** only trims the output; every input row is still read and charged. To read fewer rows use **Max input rows** or filter the data first.

**Does it work with datasets from other Actors' runs?** Yes, any dataset your account can read. Paste the `defaultDatasetId` of a run or the dataset URL from Apify Console.

**Can I group by two columns and pivot a third?** Yes: list two group-by columns and set the pivot column. Each group row then gets one column per pivot value.

### More tools from the same developer

- [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
- [Dataset Transform](https://apify.com/ucchiii/dataset-transform) — flatten, filter, rename and convert any Apify dataset, export CSV / JSON / JSONL with a link
- [Transpose Table](https://apify.com/ucchiii/transpose-table) — swap the rows and columns of a CSV, JSON or dataset table
- [Join Datasets](https://apify.com/ucchiii/dataset-join-lookup) — join two datasets or CSV/JSON files on a key column (inner, left, right, outer or VLOOKUP-style)
- [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

# Actor input Schema

## `datasetId` (type: `string`):

Dataset ID (a finished run's 'defaultDatasetId') or a dataset URL from Apify Console whose rows you want to group. You can combine it with file URLs: the dataset rows are read first. Leave this and the file URLs empty for a free demo.

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

Public http(s) links to CSV, TSV, JSON or NDJSON files, up to 20 of them and 100 MB each (JSON arrays up to 50 MB). All files are read as one table, so they should have the same columns. Links to internal networks are blocked.

## `groupBy` (type: `array`):

Column(s) whose values define a group, such as 'country' or 'category' (up to 10). Rows with the same values in all of them form one group. Nested fields work with dots (address.city). Leave empty to get one row with the totals of the whole table.

## `aggregations` (type: `array`):

List of calculations, each an object with 'name' (the output column), 'field' (the input column) and 'function': count, sum, avg, min, max, count_distinct, first, last or median. 'count' without 'field' counts rows; with a field it counts rows where that field is not empty. Empty = one 'count' column.

## `trimValues` (type: `boolean`):

Ignore spaces, tabs and line breaks (also full-width spaces) at the start and end of group-by values, so ' North ' and 'North' fall into one group. The output shows the first value seen, trimmed. Default: on.

## `ignoreCase` (type: `boolean`):

Put 'north', 'North' and 'NORTH' into one group (also used by count_distinct). Numbers always match their text form (123, 123.0 and '123' are the same group); leading zeros are kept. Default: off.

## `pivotColumn` (type: `string`):

Simple pivot table: the values of this column become output columns (for example quarter: Q1, Q2, Q3, Q4), each holding one aggregation per group. Leave empty for no pivot. At most 'Pivot: max columns' different values.

## `pivotField` (type: `string`):

The column the pivot cells are calculated from, such as 'amount'. Needed for every pivot function except 'count', which counts rows. Used only when a pivot column is set.

## `pivotFunction` (type: `string`):

How the values of one group and one pivot value are combined into the cell. Used only when a pivot column is set. Default: sum.

## `pivotFillZero` (type: `boolean`):

A group that has no row for a pivot value gets null in that column. Turn this on to write 0 instead, which is handy for sums and counts. Default: off.

## `pivotMaxColumns` (type: `integer`):

Safety limit for the number of different pivot values. If the pivot column has more, the run stops before anything is written or charged, so you do not get thousands of columns by mistake. Default: 100.

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

Name of an output column to sort the groups by: a group-by column, an aggregation name or a pivot column. Numbers sort as numbers; empty values go last. Leave empty to keep the order in which groups first appear.

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

Direction of the sort. Use descending with 'Limit' to get a top list. Used only when 'Sort by' is set. Default: ascending.

## `limit` (type: `integer`):

Keep only the first N groups after sorting, for example 10 for a top 10. All input rows are still read and charged. Leave empty to keep every group.

## `roundDecimals` (type: `integer`):

Round sums, averages and medians to this many decimals. Leave empty to keep up to 10 decimals (this only hides floating-point noise such as 0.30000000000000004).

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

Stop reading after this many input rows. This caps run time and cost ($0.70 per 1,000 rows); the result then covers only the rows read, and rows beyond the limit are not charged. Maximum 10,000,000. Default: 1,000,000.

## Actor input object example

```json
{
  "fileUrls": [
    "https://raw.githubusercontent.com/datasets/country-codes/master/data/country-codes.csv"
  ],
  "groupBy": [
    "Region Name",
    "Sub-region Name"
  ],
  "aggregations": [
    {
      "name": "countries",
      "function": "count"
    },
    {
      "name": "currencies",
      "field": "ISO4217-currency_alphabetic_code",
      "function": "count_distinct"
    },
    {
      "name": "landlocked",
      "field": "Land Locked Developing Countries (LLDC)",
      "function": "count"
    }
  ],
  "trimValues": true,
  "ignoreCase": false,
  "pivotFunction": "sum",
  "pivotFillZero": false,
  "pivotMaxColumns": 100,
  "sortOrder": "asc",
  "maxInputRows": 1000000
}
```

# Actor output Schema

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

One row per group: the group-by columns, the aggregations and the pivot columns. Download as CSV, JSON, Excel and more.

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

Record STATS: input rows read, number of groups, the output columns, rows charged and notes (for example values ignored because they were not numbers, or a stop at your limit).

# 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/datasets/country-codes/master/data/country-codes.csv"
    ],
    "groupBy": [
        "Region Name",
        "Sub-region Name"
    ],
    "aggregations": [
        {
            "name": "countries",
            "function": "count"
        },
        {
            "name": "currencies",
            "field": "ISO4217-currency_alphabetic_code",
            "function": "count_distinct"
        },
        {
            "name": "landlocked",
            "field": "Land Locked Developing Countries (LLDC)",
            "function": "count"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("ucchiii/dataset-groupby-aggregate").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/datasets/country-codes/master/data/country-codes.csv"],
    "groupBy": [
        "Region Name",
        "Sub-region Name",
    ],
    "aggregations": [
        {
            "name": "countries",
            "function": "count",
        },
        {
            "name": "currencies",
            "field": "ISO4217-currency_alphabetic_code",
            "function": "count_distinct",
        },
        {
            "name": "landlocked",
            "field": "Land Locked Developing Countries (LLDC)",
            "function": "count",
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("ucchiii/dataset-groupby-aggregate").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/datasets/country-codes/master/data/country-codes.csv"
  ],
  "groupBy": [
    "Region Name",
    "Sub-region Name"
  ],
  "aggregations": [
    {
      "name": "countries",
      "function": "count"
    },
    {
      "name": "currencies",
      "field": "ISO4217-currency_alphabetic_code",
      "function": "count_distinct"
    },
    {
      "name": "landlocked",
      "field": "Land Locked Developing Countries (LLDC)",
      "function": "count"
    }
  ]
}' |
apify call ucchiii/dataset-groupby-aggregate --silent --output-dataset

```

## MCP server setup

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

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/orbla6kJabF3NU0ZS/builds/CfPyAQPUsz95VLKK7/openapi.json
