# Python Code Runner – pandas, DuckDB & SQL on Apify Datasets (`data_daemon/python-code-runner`) Actor

Run your own Python or DuckDB SQL on rows from an Apify Dataset or a JSON array in one API call. pandas, DuckDB, pyarrow and openpyxl preinstalled, extra pip packages on request. Rows back in the Dataset; errors come back as data. About $3 per 1,000 runs.

- **URL**: https://apify.com/data_daemon/python-code-runner.md
- **Developed by:** [Daemon Data](https://apify.com/data_daemon) (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 $1.40 / 1,000 code runs

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

### What does Python Code Runner do?

**Python Code Runner** runs **your own Python or SQL on rows of data in one API call** and gives the rows back. Send the rows in the input, or point it at an **Apify Dataset** (the output of any other Actor), and write either a Python `main(rows, ctx)`, a **DuckDB SQL** query over the table `rows`, or both. **pandas, numpy, DuckDB, pyarrow and openpyxl are preinstalled**; other pip packages are installed on request. What your code returns lands in the run's Dataset in your own shape, ready as JSON, CSV or Excel, and files you save (CSV, XLSX, PNG, Parquet) land in the key-value store.

It is a code step for the places that cannot run real Python: an n8n, Make or Zapier workflow, an AI agent that needs a calculation done exactly, or a clean-up step between a scraper and a spreadsheet. A run with the sample input takes about two seconds and costs **$0.003**.

### Why use Python Code Runner?

- **Post-process another Actor's results** without downloading them: deduplicate, filter, join, pivot, compute totals, then read the result from this run's Dataset.
- **SQL on an Apify Dataset.** `SELECT company, count(*) FROM rows GROUP BY company` works on any Dataset; no database to set up.
- **A Python step for n8n, Make and Zapier** with pandas and the standard library available, called over HTTP.
- **A calculator for AI agents.** An agent sends code and rows and gets rows back, with the traceback as data when the code is wrong, so it can correct itself.
- **Scheduled scripts.** Save code and settings as a Task and put it on a schedule; API keys go in encrypted environment variables.

### How to use Python Code Runner

1. Open the **Input** tab. The form is filled with a sample: four order rows and a few lines of pandas.
2. Press **Start**. The run's Dataset holds one row per category with its total.
3. Replace the code, the rows or both. To read another Actor's results, paste its Dataset ID into **Dataset ID** and leave **Input rows** empty.
4. Read the result under **Output**, or call the Actor from your tool with the `run-sync-get-dataset-items` endpoint to get the rows in the same HTTP response.

### Input

| Field | What it is |
|---|---|
| `code` | Python 3.12. Define `main(rows, ctx)` (also `main(rows)` or `main()`, sync or async) or write a plain script that sets `result`. |
| `sql` | Optional DuckDB query. The input rows are the table `rows`. With `sql` and `code`, the SQL runs first and its result is what `main` receives. |
| `rows` | Up to 50,000 JSON objects. |
| `datasetId`, `maxRows`, `datasetOffset`, `fields` | Read up to 200,000 items of an Apify Dataset instead of `rows`. The run gets read access to that Dataset only. |
| `input` | Any JSON object; your code reads it as `ctx.input`. |
| `packages` | Up to 15 pip packages, for example `polars` or `rapidfuzz==3.9.0`. |
| `env` | Environment variables for your code, stored encrypted. The place for API keys. |
| `timeoutSecs` | Time limit for the code, 5 to 900 seconds. Default 60. |
| `failRunOnError` | Off: a failing run succeeds and returns one row with the error. On: the run ends as FAILED. |

#### Python

```python
import pandas as pd


def main(rows, ctx):
    df = pd.DataFrame(rows)
    df["total"] = df["price"] * df["qty"]
    return df.groupby("category", as_index=False)["total"].sum().sort_values("total", ascending=False)
```

`main` may return a list of dicts, one dict, a pandas DataFrame or Series, or `None`. `NaN` becomes `null` and dates become ISO strings.

`ctx` gives you:

- `ctx.rows`: the input rows; `ctx.df()`: the same as a DataFrame.
- `ctx.sql("SELECT ... FROM rows")`: DuckDB SQL on the rows, returned as a DataFrame. Pass more tables as keyword arguments: `ctx.sql("SELECT * FROM rows JOIN prices USING (sku)", prices=prices_df)`.
- `ctx.input`: the object from the `input` field.
- `ctx.save_file("report.xlsx", data)`: saves a file to the run's key-value store.

#### SQL only

```json
{
    "sql": "SELECT category, count(*) AS items, round(sum(price * qty), 2) AS total FROM rows GROUP BY category ORDER BY total DESC",
    "datasetId": "<the Dataset ID of another run>"
}
```

Nested fields work the DuckDB way: `SELECT company.name, unnest(skills) AS skill FROM rows`.

#### From n8n, Make, Zapier or any HTTP client

`POST https://api.apify.com/v2/acts/data_daemon~python-code-runner/run-sync-get-dataset-items` with your Apify token in the `Authorization: Bearer` header and this body; the response is the list of rows your code returned:

```json
{
    "code": "def main(rows):\n    return [r for r in rows if r['amount'] > 100]\n",
    "rows": [{"id": 1, "amount": 250}, {"id": 2, "amount": 40}]
}
```

### Output

The Dataset holds what your code returned, one item per row:

```json
[
    {"category": "monitors", "total": 646.0},
    {"category": "cables", "total": 114.0}
]
```

You can download the dataset in various formats such as JSON, HTML, CSV, or Excel.

The key-value store record `RUN_SUMMARY` has the status (`SUCCESS`, `ERROR`, `TIMEOUT`, `INSTALL_ERROR`, `INPUT_ERROR`), the row counts, the seconds used, everything your code printed (last 100 lines) and the traceback when it failed.

#### When your code fails

| Field | Meaning |
|---|---|
| `_status` | `ERROR` or `TIMEOUT` |
| `errorType` | The exception class, for example `KeyError` |
| `error` | The exception message |
| `traceback` | The traceback of your code, with line numbers in `your_code.py` |

With `failRunOnError` off (the default) the run succeeds and the Dataset holds that one row, so a workflow or an agent can read the error and react. With it on, the run ends as FAILED.

### How much does it cost to run Python code on Apify?

Pay per event, no subscription:

| Event | Price |
|---|---|
| Run start | $0.001 per GB of run memory |
| Code run, including the first 10 seconds | $0.002 |
| Each further 10 seconds, per GB of run memory | $0.002 |

A typical clean-up or SQL step finishes in 1-3 seconds and costs **$0.003**: about **$3 for 1,000 runs**. A 60-second job at the default 1 GB costs $0.013. Rows returned and files saved are not charged. Run time is counted from the code-run charge to the end of the run, so reading a large Dataset and installing packages count. A run never spends more than the maximum cost you set for it: the code is stopped when that limit is reached.

### Tips

- Use `fields` to read only the columns you need from a large Dataset, and give the run 2-4 GB for hundreds of thousands of rows.
- For a Dataset larger than 200,000 items, run several times with `datasetOffset`.
- Keep keys and passwords in `env`, not in the code: `os.environ["MY_API_KEY"]`.
- Save the code as a **Task** and change only `input` between Tasks.
- Your code and the packages you install run as a separate, unprivileged user inside your run's container. The Apify token and proxy password of the run are not in its environment, and it cannot read them from the runner process.

### FAQ

#### Can I run pandas in n8n Cloud?

n8n Cloud's Code node does not allow importing pandas. Call this Actor from an HTTP Request node with the body above; pandas, numpy and DuckDB are available and the response holds the rows.

#### Can I run SQL on an Apify Dataset?

Yes. Set `datasetId` and `sql`; the Dataset's items are the table `rows`. DuckDB's SQL dialect covers joins, window functions, `unnest`, JSON functions and regular expressions.

#### Which Python version and packages?

Python 3.12 with pandas, numpy, duckdb, pyarrow, openpyxl, requests, httpx, beautifulsoup4, lxml and python-dateutil. Anything else from PyPI through `packages`.

#### Can my code call the internet?

Yes: `requests` and `httpx` are installed. Calls go out from Apify's servers without a proxy.

#### Limits

50,000 inline rows, 200,000 Dataset rows in, 200,000 rows out (8 MB per row), 20 saved files of at most 50 MB each and 100 MB together, 900 seconds of code time. A DataFrame's named index (for example the keys of a `groupby`) becomes columns; an unnamed index is dropped.

#### Related Actors

Any Dataset works as input. Some from the same maker whose rows are often filtered, counted or joined afterwards:

- [IIMJobs Jobs Scraper](https://apify.com/data_daemon/iimjobs-jobs-scraper) and [Hirist.tech Jobs Scraper](https://apify.com/data_daemon/hirist-jobs-scraper): Indian management and tech jobs; count openings per company or skill with one SQL query.
- [India IPO Tracker](https://apify.com/data_daemon/india-ipo-tracker): live GMP and subscription figures; compute listing-gain estimates in pandas.
- [Dubai DLD Property Transactions](https://apify.com/data_daemon/dubai-property-transactions): registered sales; median price per square metre by community.
- [Company Domain Finder](https://apify.com/data_daemon/company-domain-finder): company name to domain and LinkedIn page; join it to any Dataset that has a company name.

#### Something is wrong or missing

Open an issue on the **Issues** tab with the run ID. More data tools from the same maker: [Daemon Data on Apify](https://apify.com/data_daemon).

# Actor input Schema

## `code` (type: `string`):

Python 3.12. Define main(rows, ctx) and return a list of dicts, one dict, a pandas DataFrame or None; or write a plain script that sets a variable named result. rows is the list of input rows. ctx.df() gives them as a DataFrame, ctx.sql('SELECT ... FROM rows') runs DuckDB SQL on them, ctx.input holds the values of the Parameters field, ctx.save_file(name, data) saves a file. Preinstalled: pandas, numpy, duckdb, pyarrow, openpyxl, requests, httpx, beautifulsoup4, lxml. Leave empty to run only the SQL.

## `sql` (type: `string`):

A DuckDB query over the input rows, which are the table named rows. Example: SELECT category, sum(price \* qty) AS total FROM rows GROUP BY category ORDER BY total DESC. With SQL only, the query result is the output. With SQL and Python, the SQL runs first and its result is what main receives as rows.

## `rows` (type: `array`):

JSON objects passed to your code, up to 50,000, for example the items of the previous n8n, Make or Zapier step. Ignored when a Dataset ID is set.

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

An Apify Dataset whose items are the input rows, for example the Dataset of another Actor's run. The run gets read access to this Dataset only. In an integration use {{resource.defaultDatasetId}}.

## `maxRows` (type: `integer`):

How many Dataset items to read in this run (1 to 200,000). The rows are held in memory: give the run more memory for large Datasets.

## `datasetOffset` (type: `integer`):

First Dataset item to read (0-based). Use it with Max Dataset rows to work through a large Dataset in several runs.

## `fields` (type: `array`):

Optional top-level field names to read from each Dataset item. Leave empty for whole items; fewer fields use less memory.

## `input` (type: `object`):

Any JSON object. Your code reads it as ctx.input, for example ctx.input\["minPrice"]. Lets you save one piece of code as several Tasks with different settings.

## `packages` (type: `array`):

Extra packages to install before the code runs, up to 15, for example polars or rapidfuzz==3.9.0. Plain names with an optional version; URLs, paths and pip options are not accepted. Installation time counts as compute time.

## `env` (type: `object`):

Stored encrypted. Your code reads them with os.environ\["NAME"]: the place for API keys and passwords your script needs. Keep them out of the code.

## `timeoutSecs` (type: `integer`):

The code is stopped after this many seconds (5 to 900). Default 60.

## `failRunOnError` (type: `boolean`):

Off (default): the run succeeds and the Dataset gets one row with \_status, error and traceback, so a workflow can branch on it. On: the run ends as FAILED, which stops an n8n, Make or Zapier workflow.

## Actor input object example

```json
{
  "code": "import pandas as pd\n\n\ndef main(rows, ctx):\n    df = pd.DataFrame(rows)\n    df[\"total\"] = df[\"price\"] * df[\"qty\"]\n    return df.groupby(\"category\", as_index=False)[\"total\"].sum().sort_values(\"total\", ascending=False)\n",
  "rows": [
    {
      "sku": "A-1",
      "category": "cables",
      "price": 12.5,
      "qty": 4
    },
    {
      "sku": "B-2",
      "category": "cables",
      "price": 3.2,
      "qty": 20
    },
    {
      "sku": "C-3",
      "category": "monitors",
      "price": 199,
      "qty": 1
    },
    {
      "sku": "D-4",
      "category": "monitors",
      "price": 149,
      "qty": 3
    }
  ],
  "maxRows": 10000,
  "datasetOffset": 0,
  "timeoutSecs": 60,
  "failRunOnError": false
}
```

# Actor output Schema

## `rows` (type: `string`):

No description

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

No description

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

No description

# 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 = {
    "code": `import pandas as pd


def main(rows, ctx):
    df = pd.DataFrame(rows)
    df["total"] = df["price"] * df["qty"]
    return df.groupby("category", as_index=False)["total"].sum().sort_values("total", ascending=False)`,
    "rows": [
        {
            "sku": "A-1",
            "category": "cables",
            "price": 12.5,
            "qty": 4
        },
        {
            "sku": "B-2",
            "category": "cables",
            "price": 3.2,
            "qty": 20
        },
        {
            "sku": "C-3",
            "category": "monitors",
            "price": 199,
            "qty": 1
        },
        {
            "sku": "D-4",
            "category": "monitors",
            "price": 149,
            "qty": 3
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("data_daemon/python-code-runner").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 = {
    "code": """import pandas as pd


def main(rows, ctx):
    df = pd.DataFrame(rows)
    df[\"total\"] = df[\"price\"] * df[\"qty\"]
    return df.groupby(\"category\", as_index=False)[\"total\"].sum().sort_values(\"total\", ascending=False)
""",
    "rows": [
        {
            "sku": "A-1",
            "category": "cables",
            "price": 12.5,
            "qty": 4,
        },
        {
            "sku": "B-2",
            "category": "cables",
            "price": 3.2,
            "qty": 20,
        },
        {
            "sku": "C-3",
            "category": "monitors",
            "price": 199,
            "qty": 1,
        },
        {
            "sku": "D-4",
            "category": "monitors",
            "price": 149,
            "qty": 3,
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("data_daemon/python-code-runner").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 '{
  "code": "import pandas as pd\\n\\n\\ndef main(rows, ctx):\\n    df = pd.DataFrame(rows)\\n    df[\\"total\\"] = df[\\"price\\"] * df[\\"qty\\"]\\n    return df.groupby(\\"category\\", as_index=False)[\\"total\\"].sum().sort_values(\\"total\\", ascending=False)\\n",
  "rows": [
    {
      "sku": "A-1",
      "category": "cables",
      "price": 12.5,
      "qty": 4
    },
    {
      "sku": "B-2",
      "category": "cables",
      "price": 3.2,
      "qty": 20
    },
    {
      "sku": "C-3",
      "category": "monitors",
      "price": 199,
      "qty": 1
    },
    {
      "sku": "D-4",
      "category": "monitors",
      "price": 149,
      "qty": 3
    }
  ]
}' |
apify call data_daemon/python-code-runner --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,data_daemon/python-code-runner"
        }
    }
}
```

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/EokV1Lm140iPjW5Er/builds/Do08733o7ZXXU81L2/openapi.json
