> ## Documentation Index
> Fetch the complete documentation index at: https://docs.declaw.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# python — pandas CSV analysis

> Upload a CSV, run a pandas analysis, and read the JSON result back — a minimal end-to-end use of the python template.

The `python` template ships `Python 3.10` with `pip`, `venv`, and `requests`,
`httpx`, `pydantic`, `numpy`, and `pandas` already installed. Pick it for
data-processing scripts, REST clients, or anything that needs `pandas` /
`numpy` without a custom build.

## What you'll learn

* Picking `template="python"` to skip a `pip install pandas` step
* Writing input data into the sandbox with `sbx.files.write`
* Running a Python analysis script and reading JSON back

## Prerequisites

<Snippet file="snippets/env-setup.mdx" />

## Code

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import json
    import textwrap

    from declaw import Sandbox


    CSV = textwrap.dedent("""\
        region,product,units,revenue
        NA,widget,120,2400
        EU,widget,80,1600
        NA,gizmo,30,1500
        EU,gizmo,55,2750
        APAC,widget,40,800
        APAC,gizmo,70,3500
    """)

    ANALYSIS = textwrap.dedent("""
        import json
        import pandas as pd

        df = pd.read_csv("/tmp/sales.csv", keep_default_na=False)
        by_region = (
            df.groupby("region")[["units", "revenue"]]
              .sum()
              .reset_index()
              .to_dict(orient="records")
        )
        top_product = (
            df.groupby("product")["revenue"]
              .sum()
              .idxmax()
        )
        out = {
            "by_region": by_region,
            "top_product": top_product,
            "total_revenue": int(df["revenue"].sum()),
            "pandas_version": pd.__version__,
        }
        with open("/tmp/result.json", "w") as f:
            json.dump(out, f)
    """)


    def main() -> None:
        sbx = Sandbox.create(template="python", timeout=120)
        try:
            sbx.files.write("/tmp/sales.csv", CSV)
            sbx.files.write("/tmp/analyze.py", ANALYSIS)

            r = sbx.commands.run("python3 /tmp/analyze.py")
            if r.exit_code != 0:
                print("analysis failed:", r.stderr)
                return

            result = json.loads(sbx.files.read("/tmp/result.json"))
            print(json.dumps(result, indent=2))
        finally:
            sbx.kill()


    if __name__ == "__main__":
        main()
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import "dotenv/config";
    import { Sandbox } from "@declaw/sdk";

    const CSV = `region,product,units,revenue
    NA,widget,120,2400
    EU,widget,80,1600
    NA,gizmo,30,1500
    EU,gizmo,55,2750
    APAC,widget,40,800
    APAC,gizmo,70,3500
    `;

    const ANALYSIS = `
    import json
    import pandas as pd

    df = pd.read_csv("/tmp/sales.csv", keep_default_na=False)
    by_region = (
        df.groupby("region")[["units", "revenue"]]
          .sum()
          .reset_index()
          .to_dict(orient="records")
    )
    top_product = df.groupby("product")["revenue"].sum().idxmax()
    out = {
        "by_region": by_region,
        "top_product": top_product,
        "total_revenue": int(df["revenue"].sum()),
        "pandas_version": pd.__version__,
    }
    with open("/tmp/result.json", "w") as f:
        json.dump(out, f)
    `;

    async function main(): Promise<void> {
      const sbx = await Sandbox.create({ template: "python", timeout: 120 });
      try {
        await sbx.files.write("/tmp/sales.csv", CSV);
        await sbx.files.write("/tmp/analyze.py", ANALYSIS);

        const r = await sbx.commands.run("python3 /tmp/analyze.py");
        if (r.exitCode !== 0) {
          console.log("analysis failed:", r.stderr);
          return;
        }

        const text = await sbx.files.read("/tmp/result.json");
        console.log(JSON.stringify(JSON.parse(text), null, 2));
      } finally {
        await sbx.kill();
      }
    }

    main().catch(console.error);
    ```
  </Tab>
</Tabs>

## Expected output

```json theme={null}
{
  "by_region": [
    {"region": "APAC", "units": 110, "revenue": 4300},
    {"region": "EU",   "units": 135, "revenue": 4350},
    {"region": "NA",   "units": 150, "revenue": 3900}
  ],
  "top_product": "gizmo",
  "total_revenue": 12550,
  "pandas_version": "2.3.3"
}
```

<Note>
  The `python` template intentionally does **not** include heavy ML packages
  (`torch`, `transformers`, `scipy`, `scikit-learn`). If you need those, build
  a custom template — see [Build a custom template](/features/templates#build-a-custom-template).
</Note>
