AI for Data Analysis
Spreadsheets of sales, attendance, survey answers or expenses hide useful answers. AI assistants can help you find them: suggest which questions to ask, write formulas, pandas or SQL code, explain results and draft a summary for your manager. They can also produce confident numbers that are simply wrong.
In this lesson you will learn the safest way to use AI for data work: describe the data instead of dumping it, ask for code instead of answers, and check every number.
Three ways AI helps with data
- Planning: "I have a year of sales data for 6 branches. What 5 questions should I answer for the annual review?"
- Writing code: formulas, pandas, SQL or chart code that you run on the real data.
- Explaining: what a chart shows, what a statistical result means, how to describe a trend in plain words.
Several assistants can also run Python on a file you upload and show the code they ran, and Copilot can work inside Excel for licensed users. These are convenient for non-confidential data, but you still need to read the code and check the results.
Why "just tell me the total" is risky
A language model reads numbers as tokens and predicts the answer as text. On a few rows it is usually right. On hundreds of rows, it may skip rows, misread a value or make an addition error, and it will still sound certain. When the model writes code and the code runs, the arithmetic is done by the computer, which does not make that kind of mistake.
So the reliable pattern is: let the AI write the analysis code, run it yourself (or check the code the tool ran), and use the AI again to help explain the results.
Describe the data, do not dump it
You rarely need to share the whole file. The model needs the column names, their types, a few sample rows and your question. This program builds such a description from a CSV file automatically, and the samples could be replaced with made-up rows if the data is sensitive:
import csv
import io
data = """date,branch,product,units,price
2026-10-01,Pune,Notebook,40,45
2026-10-01,Jaipur,Pen pack,25,60
2026-10-02,Pune,Pen pack,18,60
2026-10-02,Kochi,Notebook,32,45
2026-10-03,Jaipur,Notebook,51,45
2026-10-03,Kochi,Geometry box,12,120"""
rows = list(csv.DictReader(io.StringIO(data)))
def column_type(values):
try:
[int(v) for v in values]
return "integer"
except ValueError:
return "text"
profile = [f"The file has {len(rows)} rows and these columns:"]
for col in rows[0]:
values = [r[col] for r in rows]
profile.append(f"- {col} ({column_type(values)}), e.g. {values[0]!r}")
profile.append("Sample rows:")
profile += [", ".join(r.values()) for r in rows[:2]]
profile.append("Write pandas code to find total revenue (units * price) per branch, "
"sorted from highest to lowest. Do not calculate the answer yourself.")
print("\n".join(profile))The file has 6 rows and these columns: - date (text), e.g. '2026-10-01' - branch (text), e.g. 'Pune' - product (text), e.g. 'Notebook' - units (integer), e.g. '40' - price (integer), e.g. '45' Sample rows: 2026-10-01, Pune, Notebook, 40, 45 2026-10-01, Jaipur, Pen pack, 25, 60 Write pandas code to find total revenue (units * price) per branch, sorted from highest to lowest. Do not calculate the answer yourself.
The model now knows the structure and can write correct code, without seeing customer names, phone numbers or the full sales history.
Check the numbers
Suppose an assistant summarised the same data and said: "Jaipur had the highest revenue at ₹3,945, followed by Pune at ₹2,880." Do not copy that into a report until you have recomputed it:
import csv
import io
from collections import defaultdict
data = """date,branch,product,units,price
2026-10-01,Pune,Notebook,40,45
2026-10-01,Jaipur,Pen pack,25,60
2026-10-02,Pune,Pen pack,18,60
2026-10-02,Kochi,Notebook,32,45
2026-10-03,Jaipur,Notebook,51,45
2026-10-03,Kochi,Geometry box,12,120"""
revenue = defaultdict(int)
for row in csv.DictReader(io.StringIO(data)):
revenue[row["branch"]] += int(row["units"]) * int(row["price"])
claimed = {"Jaipur": 3945, "Pune": 2880}
for branch, total in sorted(revenue.items(), key=lambda item: -item[1]):
note = ""
if branch in claimed:
note = "matches" if claimed[branch] == total else f"AI said ₹{claimed[branch]:,}"
print(f"{branch:<7} ₹{total:>6,} {note}".rstrip())Jaipur ₹ 3,795 AI said ₹3,945 Pune ₹ 2,880 matches Kochi ₹ 2,880
Pune's figure was correct, but Jaipur's was wrong by ₹150, and the summary never mentioned that Kochi earned exactly as much as Pune. One slip like this in a report to management damages trust in everything else you write.
Good prompts for data work
I have a pandas DataFrame `df` with columns: date (datetime), branch (text),
product (text), units (int), price (int, rupees). Write code that:
1. adds a revenue column,
2. shows monthly revenue per branch as a table,
3. draws a line chart with one line per branch, with axis labels and a title.
Explain each step in one comment. Use pandas and matplotlib only.To go further, see the Data Science course, where you can run pandas code in the browser. After running the code, you can paste the summary table (not the raw data) back to the assistant and ask: "Write 4 bullet points for my manager explaining these results. Do not add numbers that are not in the table."
Common mistakes
- Pasting confidential data into public tools. Share the structure and made-up samples, or use an approved work tool.
- Accepting totals and averages without checking. Recompute them with code or a spreadsheet.
- Vague column descriptions. Say what each column means and its unit (rupees, kg, minutes).
- Confusing correlation with cause. A model may describe a pattern as a cause; ask whether the data really supports that.
Key points
- AI helps plan analyses, write formulas and code, and explain results.
- Models are unreliable at arithmetic over many rows, so ask for code and let the computer calculate.
- Describe the data with column names, types and a few (possibly made-up) sample rows instead of uploading everything.
- Recompute every number before it goes into a report.
- Ask the model to explain only the numbers you give it, not to add new ones.
Exercise
Using the same data, a model claims: "Notebooks sold 123 units in total and earned ₹5,535." Write a check that computes total units and revenue per product and prints whether each part of the claim is right.
Show solution
import csv
import io
from collections import defaultdict
data = """date,branch,product,units,price
2026-10-01,Pune,Notebook,40,45
2026-10-01,Jaipur,Pen pack,25,60
2026-10-02,Pune,Pen pack,18,60
2026-10-02,Kochi,Notebook,32,45
2026-10-03,Jaipur,Notebook,51,45
2026-10-03,Kochi,Geometry box,12,120"""
units, revenue = defaultdict(int), defaultdict(int)
for row in csv.DictReader(io.StringIO(data)):
units[row["product"]] += int(row["units"])
revenue[row["product"]] += int(row["units"]) * int(row["price"])
print("Notebook units:", units["Notebook"], "- claim 123 is", "right" if units["Notebook"] == 123 else "wrong")
print("Notebook revenue: ₹", revenue["Notebook"], "- claim 5535 is", "right" if revenue["Notebook"] == 5535 else "wrong")Notebook units: 123 - claim 123 is right Notebook revenue: ₹ 5535 - claim 5535 is right
Notebooks sold 40 + 32 + 51 = 123 units, and 123 × ₹45 = ₹5,535, so both parts of this claim are correct. Checking takes seconds, so check every time.
Quick Quiz
1. Why is it better to ask AI for analysis code than for the final numbers?
Models predict numbers as text and can slip; executed code computes exactly.
2. What should you share with a public AI tool when your data is confidential?
The structure is usually enough for the model to write correct code.
3. An AI summary says a branch earned ₹2,880. What should you do before using it?
Only an independent calculation confirms the number.
4. How should you ask for a written summary of your results?
Limiting the model to your verified numbers keeps the summary accurate.
Learn Generative AI with a mentor
Free lessons get you started. Our AI Training & Workshops training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
