---
title: How to Use AI to Write Pandas Code for Data Analysis
url: "https://goremy.ai/blog/articles/use-ai-to-write-python-and-pandas-code-for-data-analysis"
author: Luis Chavez-Mattos
editor: Luis Chavez-Mattos
editor_title: Director, Product
published: "2026-12-02T20:40:25.943Z"
updated: "2026-12-02T20:40:31.440Z"
topic: SQL and Data Analysis
description: Learn pandas with AI at your side. Get the exact prompts, a worked example, and a checklist for catching the mistakes AI makes in pandas code.
---

# How to Use AI to Write Pandas Code for Data Analysis

> Learn pandas with AI at your side. Get the exact prompts, a worked example, and a checklist for catching the mistakes AI makes in pandas code.

Edited by Luis Chavez-Mattos, Director, Product · Published 2026-12-02

## How do you use AI to write pandas code?

Describe your data to an AI assistant (column names, data types, and a few fake sample rows), state the result you want in plain English, and ask for pandas code that produces it. Run the code in small pieces in a notebook, check the output against a number you already know, and ask the AI to explain every line you don't understand. The AI writes the first draft. You own the checking, because pandas code that runs without errors can still give the wrong answer.

## TL;DR

- **Give the AI the shape of your data, not the data itself.** Column names, types and a few made-up rows are enough, and they keep confidential records out of a chat window.
- **Say what the output should look like.** "One row per region per month, with a revenue column" produces better code than "analyze my sales."
- **Run code in small pieces.** Load, filter, calculate, then summarize, checking each step before the next.
- **Verify against a number you trust.** Compare the total, a row count, or one hand-checked group with what you know from Excel or a report.
- **Use the AI as a tutor as well as a code writer.** Ask for line-by-line explanations and Excel-to-pandas translations, and you will need it less each month.
- **Watch for the known failure points.** Merges that drop or duplicate rows, silent missing values, date parsing and invented column names cause most wrong answers.

## Why move from spreadsheets to pandas?

pandas is a Python library for working with tables of data. If you have used Excel, a DataFrame (pandas' word for a table) will feel familiar: rows, columns, filters, pivots, lookups. The differences are what make analysts switch.

- Your steps are written down as code, so the analysis can be rerun next month on fresh data without redoing clicks.
- It handles files that are slow or impossible to open in a spreadsheet.
- You can review, share and version the work, so a colleague can see exactly what was done.
- Cleaning steps that take twenty minutes by hand become a few lines you reuse.

The barrier has always been syntax. You know what you want ("total revenue by region, excluding cancelled orders") but not how to spell it in code. That is the gap AI fills well.

Here is a translation table to keep nearby. You can also paste your own Excel steps into the AI and ask for the pandas equivalent.

| In Excel | In pandas |
|---|---|
| Filter a column | `df[df["status"] == "shipped"]` |
| New calculated column | `df["revenue"] = df["qty"] * df["price"]` |
| SUMIF / SUMIFS | `df.groupby("region")["revenue"].sum()` |
| Pivot table | `df.pivot_table(index="region", columns="month", values="revenue", aggfunc="sum")` |
| VLOOKUP / XLOOKUP | `df.merge(other, on="customer_id", how="left")` |
| Remove duplicates | `df.drop_duplicates(subset="order_id")` |
| Sort | `df.sort_values("revenue", ascending=False)` |
| Text to columns | `df["name"].str.split(" ", expand=True)` |

## What do you need before you start?

Three things.

**A place to run Python.** The easiest options for a beginner are a Jupyter notebook, VS Code with its notebook support, or Google Colab, which runs in a browser with nothing to install. Check with your IT team what is allowed on a work machine. Many companies provide an approved Python environment.

**An AI assistant.** Any of the major chat assistants can write pandas. Some notebook tools also build an assistant into the editor so it can see your error messages. Use whatever your company has approved.

**A data-handling rule.** Before pasting anything, check your company's AI policy. The safe default: never paste real customer, employee or financial records into a public AI tool. You rarely need to. The AI needs the structure of the data, not the contents. Step 1 below shows how to generate that description safely.

## How do you write pandas code with AI, step by step?

### 1. Describe the data without sharing it

Load your file in your notebook and run these three lines:

```python
import pandas as pd

df = pd.read_csv("orders.csv")
df.info()
df.head(3)
```

`df.info()` lists every column, its data type and how many values are filled in. That output is what the AI most needs. Copy it. For the `head(3)` rows, replace anything sensitive with invented values before pasting, or skip them and describe the columns in words ("order_date is text like 2025-03-14").

Also run `pd.__version__` and note the result. Newer and older pandas versions differ, and AI sometimes writes code for the wrong one.

### 2. Write a prompt with a goal, a structure and an output shape

Vague requests get vague code. Use this template.

```
I'm analyzing data in Python with pandas (version [X]). I'm new to pandas,
so keep the code simple and add a short comment on each step.

My DataFrame is called df. Here is its structure from df.info():
[paste df.info() output]

Three example rows (made-up values):
[paste fake rows]

Goal: [what question you are answering, in business terms]

Rules:
- [e.g. exclude rows where status is "cancelled"]
- [e.g. revenue = quantity * unit_price]

Output: [exact shape, e.g. "one row per region per month, columns:
region, month, revenue, mom_change_pct"]

Give me the code in separate blocks I can run one at a time, and tell me
what to check after each block.
```

The last line matters. It makes the AI split the work into steps and tell you what to inspect.

### 3. Run it one block at a time

Paste the first block, run it, and look at the result. Do not paste the whole script and run it at once. When something goes wrong in step two of six, you want to know it is step two.

### 4. Check the result against something you know

This is the step that separates a useful analysis from a confident wrong answer. Pick at least one:

- **Row counts.** How many rows before and after each filter or merge? Does the change make sense?
- **A known total.** Does total revenue match the figure in the finance report or your old spreadsheet?
- **One hand-checked slice.** Pick one region and one month, filter the raw data in Excel, and compare.
- **Value lists.** Run `df["status"].value_counts()` to see every spelling that exists. "Cancelled", "cancelled" and "CANCELED" are three different values to pandas.

### 5. Ask the AI to explain what it wrote

For any line you can't read, ask:

```
Explain this code line by line as if I know Excel but not Python.
For each line, say what the data looks like before and after it runs.

[paste code]
```

### 6. Fix errors by feeding them back

When you get an error, paste the full error message and the code that caused it, plus one sentence on what you expected. Most pandas errors (a wrong column name, a type mismatch, a missing import) get fixed in one round.

### 7. Save the working version

Once the analysis is right, ask the AI to turn the blocks into one script with a function and clear comments, so next month you change a filename and rerun.

## What does a worked example look like?

Say you have an orders file with these columns: `order_id`, `customer_id`, `order_date`, `region`, `product`, `quantity`, `unit_price`, `status`. Your manager wants monthly revenue by region, excluding cancelled orders, with the percentage change from the previous month.

Your prompt (after the template's structure section):

```
Goal: monthly revenue by region, with month-over-month percentage change.
Rules: exclude rows where status is "cancelled" (check for different
spellings first). Revenue = quantity * unit_price.
Output: one row per region per month with columns region, month, revenue,
mom_change_pct.
```

A good AI answer looks something like this:

```python
import pandas as pd

orders = pd.read_csv("orders.csv", parse_dates=["order_date"])

# Check status spellings before filtering
print(orders["status"].value_counts())

valid = orders[orders["status"].str.lower() != "cancelled"].copy()
valid["revenue"] = valid["quantity"] * valid["unit_price"]
valid["month"] = valid["order_date"].dt.to_period("M")

monthly = (
    valid.groupby(["region", "month"], as_index=False)["revenue"]
    .sum()
    .sort_values(["region", "month"])
)

monthly["mom_change_pct"] = (
    monthly.groupby("region")["revenue"].pct_change() * 100
)

print(monthly.head(12))
```

Now run your checks:

1. **Row counts.** Compare `len(orders)` with `len(valid)`. The difference should equal the number of cancelled orders from `value_counts()`.
2. **Total.** Compare `monthly["revenue"].sum()` with `(valid["quantity"] * valid["unit_price"]).sum()`. They must match exactly.
3. **One slice.** Filter your original data in Excel to one region and month and compare to the matching row.
4. **A subtle problem.** If a region had no orders in some month, that month will be missing from `monthly`, and `pct_change()` will compare against the last month that exists, not the previous calendar month. This is the kind of issue the AI will not flag unless you ask. A follow-up prompt fixes it:

```
Some regions have months with no orders. Change the code so every region
has a row for every month in the date range, with revenue 0 where there
were no orders, before calculating the percentage change. Note that
dividing by zero will produce infinity, so show those as blank instead.
```

That follow-up is a normal part of the process. The first answer gets you 80 percent of the way, and your knowledge of the business covers the rest.

## Where can't you trust AI-written pandas code?

AI writes fluent code, and fluent is not the same as correct. These are the failure points that come up most often.

- **Merges that change your row count.** An inner merge silently drops unmatched rows. A merge on a column with duplicates multiplies rows. After any merge, compare row counts and ask the AI to add `validate="many_to_one"` (or the right relationship) so pandas raises an error when the keys don't behave as expected.
- **Missing values.** By default, `groupby` drops rows where the grouping column is blank. Averages skip blanks. Both can change totals without a warning. Run `df.isna().sum()` early and decide how to treat blanks on purpose.
- **Dates.** A date like 03/04/2025 can mean March 4 or April 3. If your data uses day-first dates, tell the AI and check a few parsed values.
- **Invented or misspelled columns.** If you left out the column list, the AI will guess names. Always include `df.info()`.
- **Outdated methods.** AI tools learned from years of older code. Some methods (`DataFrame.append` is a well-known example) were removed in pandas 2.0. Tell the AI your version and paste back any deprecation warnings.
- **Averages of averages.** Averaging regional averages is not the same as the company-wide average. When a metric is a ratio, ask which rows it should be weighted by.
- **Plausible but wrong business logic.** The AI doesn't know that "revenue" at your company excludes refunds, or that fiscal years start in July. Put definitions in the prompt.

A useful habit: after you get working code, ask a second prompt, "Review this code for bugs, silent data loss, and assumptions I should verify. List them." It will not catch everything, but it often finds the merge and missing-value issues.

## What other prompts are worth keeping?

Save these in a notes file and adjust the brackets.

**Translate an Excel process:**

```
Here is how I do this in Excel: [describe steps, e.g. "VLOOKUP the region
from the customers sheet using customer_id, filter to 2025, pivot by
region and product, sum of revenue"]. Write the pandas equivalent using
these DataFrames: [paste df.info() for each].
```

**Clean messy data:**

```
Based on df.info() and these value counts [paste], write code that:
standardizes the text in [column] (trim spaces, consistent case), converts
[column] to a date, and flags rows I should review rather than deleting
them. Don't drop any rows silently.
```

**Debug:**

```
This code gave the error below. Explain what the error means in plain
English, then give the fix.
Code: [paste]
Error: [paste full error]
```

**Check your own work:**

```
I wrote this pandas code. Don't rewrite it. List anything that could give
wrong numbers: merges, missing values, duplicates, data types.
```

## How do you learn pandas faster with AI?

Copying code teaches you very little. A better loop:

1. Ask the AI for the code and run it.
2. Ask it to explain each line.
3. Close the chat and rewrite the same analysis from memory, looking up only what you forgot.
4. Paste your version back and ask for a review: what is unclear, what could break, what a more common approach would be.
5. Ask it to give you three practice questions on the same data, with answers hidden until you try.

Within a few weeks you will notice you are asking for fewer complete solutions and more for single functions you can't recall. That is the goal. The AI becomes a reference book you can talk to, and you make the decisions.

Learn these building blocks first, since most analysis uses them: `read_csv`, selecting and filtering rows, `groupby`, `merge`, `pivot_table`, `to_datetime`, and `isna`. Ask the AI to teach each one using your own column names so the examples feel real.

## Can you turn your pandas analysis into a tool other people use?

A notebook works well for you, but your colleagues usually want a page they can open, not a Python file to run. If your analysis repeats each month (upload the new export, see the regional revenue table, filter by product), you can describe that workflow to [Remy](https://goremy.ai) in plain English and have it build a small web app with sign-in, a database and a live URL. That replaces emailing spreadsheets around or buying another reporting subscription. Keep pandas for exploring and proving the logic. Once you know what the report should show, writing it down as a clear description is the first step toward software your team owns.

## Frequently Asked Questions

### Do I need to know Python before using AI to write pandas code?

No, but you need to learn to read it. Start with small tasks, run each block, and ask the AI to explain every line. After a few real projects you will recognize the common patterns. Reading and checking code is a smaller skill than writing it from scratch, and AI makes it possible to start with that one. If you are starting from zero, a [realistic plan for learning to code with AI](https://goremy.ai/blog/articles/learn-to-code-as-an-adult-with-ai) covers which language to pick and what to build first.

### Is it safe to paste company data into an AI chat?

Not by default. Check your company's AI and data policy first. You usually don't need to paste real data: the output of `df.info()` and a few invented example rows give the AI what it needs. If your company provides an approved AI tool for internal data, use that one.

### Can AI replace learning pandas entirely?

It can write most routine code, but you still have to judge whether the result is right. That requires knowing what a merge does, how blanks are treated and what the output should look like. Treat AI as a fast tutor and drafting partner, and keep building your own understanding.

### Why does my AI-written pandas code run but give the wrong numbers?

The usual causes are a merge that dropped or duplicated rows, blank values being skipped, text spellings that did not match your filter, or a business definition the AI had to guess. Compare row counts at each step, check a total against a known figure, and spell out your definitions in the prompt.

### What is the difference between asking AI for pandas code and using AI inside Excel?

Excel's built-in AI features work on the sheet in front of you and keep results in the workbook. Pandas code is a written, repeatable procedure that handles larger files and can be rerun, reviewed and shared. For one-off questions on small data, the spreadsheet route is fine. For recurring analysis, code pays off.
