ChatGPT for Data Analysis — Python Workflow Guide 2026

Sanjeev SharmaSanjeev Sharma
6 min read

Advertisement

Introduction

Why This Matters

ChatGPT accelerates data analysis by generating pandas transformations, writing SQL aggregations, suggesting visualization approaches, and interpreting results — all from plain-language descriptions. This cuts the time from "I have this dataset" to "I have actionable insights" significantly. This guide covers practical workflows for data engineers, analysts, and scientists using Python.

Using ChatGPT's Code Interpreter

The Code Interpreter tool in ChatGPT Plus executes Python in a sandboxed environment. Upload a CSV or Excel file and ask natural language questions:

Workflow:
1. Open chat.openai.com with ChatGPT Plus
2. Start a new conversation with GPT-4o
3. Click the attachment icon and upload your dataset
4. Ask: "Give me a summary of this dataset: column types,
   missing values, basic statistics, and any obvious data quality issues."
5. Follow up: "Plot the distribution of [column] and identify outliers."
6. Export the generated code to use in your own environment

This is the fastest path to exploratory analysis — no environment setup needed.

Generating Pandas Code via the API

For programmatic workflows, describe your transformation and let the API generate the code:

from openai import OpenAI
import pandas as pd
 
client = OpenAI()
 
def generate_pandas_code(dataset_description: str, task: str) -> str:
    """Generate pandas code for a data transformation task."""
    prompt = f"""
Write Python pandas code to perform the following task.
Use only pandas and numpy. No matplotlib unless explicitly requested.
Return only the code, no explanation.
 
Dataset: {dataset_description}
Task: {task}
"""
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=1024,
        temperature=0.0,
    )
    return response.choices[0].message.content
 
# Example usage
dataset_info = """
DataFrame with columns:
- user_id (int): unique user identifier
- purchase_date (str): date in YYYY-MM-DD format
- amount (float): purchase amount in USD
- category (str): product category
- country (str): user country
"""
 
code = generate_pandas_code(
    dataset_info,
    "Calculate monthly revenue by country, pivot the result so months are columns, "
    "and sort by total annual revenue descending."
)
print(code)

Exploratory Data Analysis Template

import pandas as pd
from openai import OpenAI
 
client = OpenAI()
 
def describe_dataframe(df: pd.DataFrame) -> str:
    """Create a text description of a DataFrame for the LLM."""
    description = f"""
Shape: {df.shape[0]} rows, {df.shape[1]} columns
 
Column types:
{df.dtypes.to_string()}
 
Missing values:
{df.isnull().sum().to_string()}
 
Numeric summary:
{df.describe().to_string()}
 
Sample rows (first 5):
{df.head(5).to_string()}
"""
    return description
 
def get_analysis_suggestions(df: pd.DataFrame, business_question: str) -> str:
    """Ask ChatGPT what analyses to run given a business question."""
    df_description = describe_dataframe(df)
 
    prompt = f"""
You are a data scientist helping analyze this dataset.
 
Dataset overview:
{df_description}
 
Business question: {business_question}
 
Suggest:
1. The top 3 most valuable analyses to answer this question
2. The pandas code for each analysis
3. What visualization would best communicate each result
"""
 
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=2048,
        temperature=0.2,
    )
    return response.choices[0].message.content
 
# Usage
df = pd.read_csv("sales_data.csv")
suggestions = get_analysis_suggestions(
    df,
    "Why did revenue drop 15% in Q3 compared to Q2?"
)
print(suggestions)

Automated Report Generation

Build a pipeline that analyzes data and writes a narrative report:

import pandas as pd
from openai import OpenAI
 
client = OpenAI()
 
def generate_report(df: pd.DataFrame, report_type: str = "executive_summary") -> str:
    """Generate a data analysis report from a DataFrame."""
 
    # Compute key metrics
    metrics = {
        "total_revenue": df["amount"].sum(),
        "avg_order_value": df["amount"].mean(),
        "total_orders": len(df),
        "top_category": df.groupby("category")["amount"].sum().idxmax(),
        "top_country": df.groupby("country")["amount"].sum().idxmax(),
        "month_over_month_change": (
            (df[df["month"] == df["month"].max()]["amount"].sum()
             - df[df["month"] == df["month"].max() - 1]["amount"].sum())
            / df[df["month"] == df["month"].max() - 1]["amount"].sum() * 100
        ) if "month" in df.columns else None,
    }
 
    prompt = f"""
Write a concise {report_type} data analysis report based on these metrics.
 
Metrics:
- Total Revenue: ${metrics['total_revenue']:,.2f}
- Average Order Value: ${metrics['avg_order_value']:.2f}
- Total Orders: {metrics['total_orders']:,}
- Top Category: {metrics['top_category']}
- Top Country: {metrics['top_country']}
 
Format: 3-4 bullet points highlighting the most important insights.
End with one actionable recommendation.
Tone: professional, data-driven, concise.
"""
 
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=512,
        temperature=0.3,
    )
    return response.choices[0].message.content

Natural Language SQL Generation

SCHEMA = """
Tables:
- orders (id, user_id, created_at, total_amount, status)
- users (id, email, country, created_at, subscription_tier)
- order_items (id, order_id, product_id, quantity, unit_price)
- products (id, name, category, base_price)
"""
 
def generate_sql(question: str, schema: str = SCHEMA) -> str:
    """Convert a natural language question into a SQL query."""
    prompt = f"""
Convert this business question into a SQL query.
Database schema:
{schema}
 
Question: {question}
 
Requirements:
- Use standard SQL (PostgreSQL compatible)
- Include comments explaining complex parts
- Handle NULL values appropriately
- Return only the SQL query, no explanation
"""
 
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=512,
        temperature=0.0,
    )
    return response.choices[0].message.content
 
sql = generate_sql(
    "What is the average order value by country for premium users in the last 90 days?"
)
print(sql)

Common Mistakes

  • Sending full raw datasets to the API — send statistics and schemas instead to stay within context limits and avoid exposing sensitive data
  • Not specifying the output format — "give me pandas code" without context produces generic boilerplate
  • Trusting generated SQL on production databases without review — always test on a read replica
  • Not describing the dataset schema precisely — incorrect column names cause wrong output
  • Using ChatGPT to interpret results without providing business context — insights lack relevance

Best Practices

  • Send statistical summaries (.describe(), .dtypes, .head()) rather than raw rows — richer signal, fewer tokens
  • Use temperature=0.0 for code generation to get deterministic, reproducible output
  • Validate generated pandas code on a small sample before running on the full dataset
  • Mask or anonymize sensitive columns before including any sample rows in prompts
  • Build reusable prompt templates for your most common analysis patterns

Key Takeaways

  • ChatGPT's Code Interpreter (ChatGPT Plus) executes Python in a sandbox — the fastest path to exploratory analysis without any setup
  • Sending .describe(), .dtypes, and .head() output gives the model everything it needs without exposing full raw data
  • temperature=0.0 is optimal for pandas and SQL code generation — maximizes determinism and correctness
  • Natural language SQL generation works well for schema-described databases; always validate queries on a non-production replica
  • Automated narrative report generation is effective when you pre-compute metrics and pass them as structured input
  • Function calling + data analysis creates powerful pipelines where the model decides which transformations to apply
  • Never send production data containing PII or financial records to external APIs without legal review
  • Generated code requires validation — run it on a sample before applying to the full dataset

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro

Related reading