Python Code Runner – pandas, DuckDB & SQL on Apify Datasets avatar

Python Code Runner – pandas, DuckDB & SQL on Apify Datasets

Pricing

from $1.40 / 1,000 code runs

Go to Apify Store
Python Code Runner – pandas, DuckDB & SQL on Apify Datasets

Python Code Runner – pandas, DuckDB & SQL on Apify Datasets

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.

Pricing

from $1.40 / 1,000 code runs

Rating

0.0

(0)

Developer

Daemon Data

Daemon Data

Maintained by Community

Actor stats

0

Bookmarked

2

Total users

1

Monthly active users

a day ago

Last modified

Features

Limited permissions

Share

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

FieldWhat it is
codePython 3.12. Define main(rows, ctx) (also main(rows) or main(), sync or async) or write a plain script that sets result.
sqlOptional DuckDB query. The input rows are the table rows. With sql and code, the SQL runs first and its result is what main receives.
rowsUp to 50,000 JSON objects.
datasetId, maxRows, datasetOffset, fieldsRead up to 200,000 items of an Apify Dataset instead of rows. The run gets read access to that Dataset only.
inputAny JSON object; your code reads it as ctx.input.
packagesUp to 15 pip packages, for example polars or rapidfuzz==3.9.0.
envEnvironment variables for your code, stored encrypted. The place for API keys.
timeoutSecsTime limit for the code, 5 to 900 seconds. Default 60.
failRunOnErrorOff: a failing run succeeds and returns one row with the error. On: the run ends as FAILED.

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

{
"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:

{
"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:

[
{"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

FieldMeaning
_statusERROR or TIMEOUT
errorTypeThe exception class, for example KeyError
errorThe exception message
tracebackThe 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:

EventPrice
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.

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

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.