Analyzing CSV and Spreadsheet Data
From "File Uploaded" to "Correct Analysis"
Lesson 3 covered getting a file into the sandbox. This lesson covers the part that actually determines whether the analysis is useful: how to phrase requests so the model writes correct, well-scoped pandas code against that file, how to handle the quirks specific to CSVs and Excel workbooks, and how to structure a conversation that goes from raw data to real insight without wasting turns.
A Baseline Example
Start with a small, realistic dataset and a direct request:
from openai import OpenAI
client = OpenAI()
uploaded = client.files.create(file=open("orders.csv", "rb"), purpose="assistants")
response = client.responses.create(
model="gpt-5.6-terra",
tools=[{
"type": "code_interpreter",
"container": {"type": "auto", "file_ids": [uploaded.id]},
}],
input=(
"The file orders.csv has columns order_id, customer_id, order_date, "
"amount, and region. Load it with pandas, confirm the row count and "
"column dtypes, and report total amount by region sorted descending."
),
)
print(response.output_text)
Notice that the prompt does three specific things beyond just naming the file: it lists the expected columns, it asks for a sanity check (row count and dtypes) before the actual analysis, and it states the exact aggregation wanted (sum of amount, grouped by region, sorted descending). Each of these reduces ambiguity that would otherwise force the model to guess. A vague prompt like "analyze this file" produces a much less predictable result — the model has to decide on its own what "analyze" means, and different runs can emphasize different things.
Why Describing the Schema Helps
You might reasonably ask why you should describe columns the model can simply inspect by reading the file's header. It can, and typically will, run something like pd.read_csv(...).head() early in its own generated code to look. But stating the schema up front does two things a purely exploratory approach does not:
- It lets the model write the entire analysis in a single, correct execution rather than needing an exploratory step followed by a corrective one, which saves both latency and tool-call overhead.
- It gives you, the developer, a place to catch a schema mismatch immediately. If your prompt says
amountand the real file hasorder_amount, the model's own inspection step will surface that discrepancy in its response, and you'll see it — but if you already know your schema, stating it is cheap and removes the failure mode entirely for cases where you control the upstream data format.
Handling Data Quality Issues
Real datasets have missing values, inconsistent types, and outliers. Code interpreter handles this well when the prompt asks for it explicitly:
response = client.responses.create(
model="gpt-5.6-terra",
tools=[{
"type": "code_interpreter",
"container": {"type": "auto", "file_ids": [uploaded.id]},
}],
input=(
"Load orders.csv. Report how many rows have a null value in any "
"column, and how many rows have a negative or zero value in the "
"amount column. Then compute total amount by region using only "
"rows that pass both checks."
),
)
print(response.output_text)
This prompt separates diagnosis (how much bad data is there) from the actual computation (the cleaned aggregate), and asks for both. This is a meaningfully better pattern than just asking for "the total by region," because a silent filtering decision made by the model without your knowledge is exactly the kind of thing that erodes trust in an automated analysis pipeline — you want to see, in the output, what was excluded and why.
Working with Excel Files and Multiple Sheets
Excel workbooks introduce a wrinkle CSVs do not have: a single file can contain multiple sheets, and pandas needs to be told which one to read.
uploaded = client.files.create(file=open("regional_report.xlsx", "rb"), purpose="assistants")
response = client.responses.create(
model="gpt-5.6-terra",
tools=[{
"type": "code_interpreter",
"container": {"type": "auto", "file_ids": [uploaded.id]},
}],
input=(
"regional_report.xlsx has multiple sheets. First list all sheet "
"names in the workbook. Then load the sheet named 'Q1_Sales' and "
"report the top 5 products by units sold."
),
)
print(response.output_text)
Asking for the sheet names first, in the same prompt, is a small but effective technique: it forces the model's generated code to call something equivalent to pd.ExcelFile(path).sheet_names before assuming a sheet exists, which avoids a common failure where the model guesses a sheet name (often something generic like "Sheet1") that does not match your actual workbook.
For workbooks where you already know the exact sheet name, skip the discovery step and just state it — one fewer round of exploration, one fewer chance for the model to load the wrong data.
Multi-Step Analysis Using Container Reuse
For any analysis with more than one logical question, use the container-reuse pattern from Lesson 2 rather than trying to cram every question into one prompt:
first = client.responses.create(
model="gpt-5.6-terra",
tools=[{
"type": "code_interpreter",
"container": {"type": "auto", "file_ids": [uploaded.id]},
}],
input="Load orders.csv into a dataframe called df and report its shape.",
)
second = client.responses.create(
model="gpt-5.6-terra",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
previous_response_id=first.id,
input="Using df, compute average order amount per month.",
)
third = client.responses.create(
model="gpt-5.6-terra",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
previous_response_id=second.id,
input="Now filter df to only the region with the highest average order amount from the previous step, and report its top 3 customers by total spend.",
)
print(third.output_text)
Each step builds on df as an already-loaded, already-validated dataframe, and the third question explicitly references "the previous step's result" in natural language, which the model can resolve because the conversation history — including the actual computed values — is available to it through the chained responses. This is both cheaper (the file is parsed once, not three times) and more coherent than three independent requests, because the model isn't re-deriving the same intermediate result each time and risking a slightly different answer due to a different code path.
Common Mistakes
Asking an open-ended question against a large, unfamiliar file. "Tell me what's interesting in this data" against a 50-column file forces the model to make numerous unstated judgment calls about what "interesting" means, and different runs will emphasize different columns. Ground the request in specific columns and specific statistics whenever you know what you are looking for.
Not accounting for header rows or metadata rows in exported spreadsheets. Files exported from business intelligence tools sometimes have a title row or a blank row before the real header. If you know this about your file format, say so in the prompt ("the real header is on row 3") rather than letting the model discover and potentially misparse it.
Re-uploading and re-describing the same file for every follow-up question. This wastes tokens and sandbox time, and — because it does not reuse the same loaded dataframe — can occasionally produce a subtly different reload (for example, a different automatic type inference) than the one the earlier answer was based on. Use container reuse instead, as shown above.
Best Practices
State column names and expected types explicitly when you know your data's schema. This removes ambiguity and gives you an early signal if the actual file does not match what you expected.
Separate data-quality diagnosis from the final computed answer in your prompt, so that filtering decisions are visible in the output rather than silently baked into a single aggregate number.
Chain multi-question analyses with previous_response_id rather than independent calls, so later questions can build on already-validated, already-loaded state instead of redoing the same work with a chance of subtly different results each time.