Skip to content

DS 202 · Module 1

AI-Assisted Analysis: From Question to Executable Code

Starting from a service analysis package, practice judging what AI can and cannot do in data-science work, supplying enough data context, writing a verifiable analysis prompt, and reading AI-generated code before you run it.

Start Section 1
0 / 5 completed
Sync my progressJoin a session to keep progress across devices and share it with your instructor

Info

After you join, your completed lesson numbers are sent to your instructor together with your learner code, so they can see your progress. Use the codes your instructor gave you, and do not enter your name, company secrets or other personal data. Progress is kept with the rest of that session's data.

Learning objectives

  • Map AI roles across framing, code, debugging, interpretation, documentation; retain human responsibility
  • Provide schema, grain, units, allowed operations, and forbidden assumptions
  • Write task/context/requirements/output/verification prompts for data analysis
  • Review imports, columns, filters, joins, formulas, side effects, and expected outputs before execution
  • Use AI to propose and implement an analysis, then independently verify each critical step

What AI Can and Cannot Do in Data Science

35 min

What AI Can and Cannot Do in Data Science

Learning goal: map AI roles across framing, code, debugging, interpretation, documentation; retain human responsibility.

You hand an AI assistant the "Analysis Package" dataset and ask: "Tell me which group most needs attention." It quickly returns a block of code, a chart, and a conclusion: "Group unit_b has the worst numbers; recommend reinforcing it first." That answer looks complete, but it hides several unchecked assumptions: does the AI realize the unit column determines which metric value actually represents this time (case volume, response hours, cost per case...)? Did it exclude rows still marked draft or superseded that should not feed a live analysis? Without a human check, this fluent-sounding conclusion may just be a well-written mistake.

Treating AI output as the answer

"AI says group unit_b has the worst numbers" is quoted straight into the report, with nobody confirming which metric the value column represents this time, or whether draft, superseded, and validated rows were mixed together.

Treating AI output as a proposal, verified by a person

What AI can do
Quickly list candidate angles for analysis, draft code, flag possible data issues, translate statistics into plain language, and assemble a documentation draft.
What AI cannot do
It cannot confirm whether a column's business definition is correct, cannot guarantee the code truly understands the data's grain, and cannot stand in for a human being responsible for the final conclusion.
What a person must do
Confirm the data context, review the critical code line by line, verify the conclusion truly follows from the data, and make the call that the result is trustworthy before it is delivered.
The course dataset (check the schema before trusting any conclusion)
import pandas as pd

# clean: the Analysis Package dataset, one row per capacity record for a service group in a given period
df = pd.read_csv("DS202_Analysis_Package_Clean.csv", parse_dates=["period"])
df.shape
df.dtypes
df[["record_id", "period", "group", "value", "unit", "status"]].head()

# Ask first: what unit does value use this time? How many status values exist?
df["unit"].unique()
df["status"].unique()
AI's reasonable role in an analysis workflow
StageWhat AI is good atWhat a person must still confirm
FramingList candidate prediction problems or analysis anglesWhich angle truly maps to a business decision
CodeDraft loading, cleaning, and aggregation codeWhether column definitions, units, and grain are used correctly
DebugFlag possible errors or inconsistenciesWhether the conclusion needs re-checking once the fix is applied
InterpretationTranslate statistical results into a plain-language summaryWhether the summary is more optimistic or definitive than the data supports
DocumentationAssemble prompts, code, and conclusions into a draft documentWhether the document honestly reflects limitations and what was not verified
Case: the same value, two completely different stories

The same analysis group has a value of 58.4 for some month. If this represents case volume (unit=count), 58.4 cases is a light workload; if it represents average response hours (unit=hours), 58.4 hours is a serious overtime warning. AI's conclusion "58.4, on the high side" could be read either way, and only one reading is correct, unless the unit is confirmed first.

  • Confirm which unit (metric) value represents this time, before judging whether a number is high or low
  • Confirm whether rows with status draft or superseded have been excluded
  • Confirm whether rows with sensitive_flag true, which should not flow into a general analysis, have been excluded
  • Confirm the group and period scope being aggregated actually matches the question you want answered

Warning

Data safety reminder: every exercise in this course uses course-provided synthetic data. Unless authorized, never paste confidential institutional data, client personal data, or other unauthorized sensitive information into an AI tool or the practice environment.

Info

Human, AI, Human: a person defines the analysis question and scope; AI may help draft code and explanations; a person verifies the data, code, and conclusion item by item and remains responsible for what is delivered.
Check yourself

An AI assistant gives a fluent analysis conclusion about the service data, and the code ran cleanly with no error messages. What does this actually tell you?

An AI assistant gives a fluent analysis conclusion about the service data, and the code ran cleanly with no error messages. What does this actually tell you?

Key takeaway: Completing the steps is not enough; the result must be verifiable, reproducible, and explainable.

Data Context: Schema, Definitions, Constraints

40 min

Data Context: Schema, Definitions, Constraints

Learning goal: provide schema, grain, units, allowed operations, and forbidden assumptions.

A colleague hands AI a file path and says only "compute the average value per group," without mentioning that the unit column doubles as both a measurement unit and a metric identifier (unit "count" means case volume; unit "hours" means average response time), and without mentioning that the status column has three values (validated, draft, superseded) and not every row is ready to analyze. To complete the task, the AI has to guess a set of assumptions on its own: for example, that the whole value column represents one single metric, or that every row is already approved. Those assumptions are rarely spoken aloud, but they are enough to make the entire analysis wrong from the start.

Five things to state when providing data context
ItemThis dataset's answer
Schemarecord_id, period, group, value, unit, status, sensitive_flag, source_version
Grain (what one row represents)One analysis value for one group, in one period, for one metric (unit)
Unitsunit is both the unit and the metric identifier: count = case volume, hours = average response time, percent = satisfaction score, cases = backlog cases, usd = cost per case; never assume every row is the same metric
Allowed operationsGrouping and aggregation by group, period, and unit is fine; aggregating across units has no meaning, since that mixes different metrics
Forbidden assumptionsNever assume every status is validated; filter out draft and superseded rows before analysis
Confirm this context yourself before writing the prompt
import pandas as pd

df = pd.read_csv("DS202_Analysis_Package_Clean.csv", parse_dates=["period"])

# Grain check: is group + period + unit unique?
df.groupby(["group", "period", "unit"]).size().max()

# What unit values exist? Each one determines which metric this row is.
df["unit"].unique()

# Status distribution: are there rows not yet ready to analyze (draft, superseded)?
df["status"].value_counts()
  1. Write out the schema and types
    List every column's name, type, and allowed values; never assume AI already knows them.
  2. Define the grain
    State clearly what one row represents, and whether duplicates or version relationships exist.
  3. Flag units and conversion rules
    If one column carries different units across rows, say so explicitly and state the conversion or grouping rule.
  4. List forbidden assumptions
    Write out explicit "do not assume..." statements, such as never assuming every row's status is already validated.
How much AI's answer changes with and without context

Without context: "Group unit_b has an average of 58.4, the highest of all groups." With a full schema, grain, and forbidden assumptions supplied: "Counting only rows where unit equals count and status equals validated, group unit_b's average case volume is 112; the original 58.4 actually mixed count and usd metrics and included 3 not-yet-approved draft rows."

  • Have every column's name, type, and allowed values been listed out?
  • Has it been stated what one row represents, and whether duplicates or version relationships exist?
  • If one column carries different units, has the conversion or grouping rule been made explicit?
  • Is the "do not assume..." forbidden list more explicit than the list of what is allowed?

Warning

Without schema and grain, AI will not tell you it is guessing: it will simply produce a complete-looking answer. Errors from guessing a column's meaning wrong are usually harder to catch than a code syntax error.
Check yourself

You ask AI to "compute the average value per group" without mentioning that the unit column determines which metric this row represents (for example, count means case volume, hours means average response time). What is the most likely problem?

You ask AI to "compute the average value per group" without mentioning that the unit column determines which metric this row represents (for example, count means case volume, hours means average response time). What is the most likely problem?

Key takeaway: Completing the steps is not enough; the result must be verifiable, reproducible, and explainable.

From Analysis Need to Verifiable Prompt

40 min

From Analysis Need to Verifiable Prompt

Learning goal: write task/context/requirements/output/verification prompts for data analysis.

"Please analyze this data for me" is a task, but not a verifiable prompt. A verifiable prompt is one where you can later check whether AI actually did what you asked. Breaking a prompt into five parts: task (what to do), context (what the data is), requirements (constraints and rules), output (the output format), verification (what to attach so a person can check it) sharply reduces the room AI has to fill in its own assumptions.

A vague prompt

"Tell me which group has the highest case volume, and make a chart." No statement of which metric value represents here, no statement on whether to exclude rows not yet approved, no requirement for supporting evidence in the output.

A structured, verifiable prompt

Task
Compute the 2026 monthly average "case volume" (rows where unit is count, i.e. the request_volume metric) per group, and identify the highest group.
Context
Columns are record_id, period, group, value, unit, status, sensitive_flag, source_version; unit determines which metric this row represents, and status has three values: validated, draft, superseded.
Requirements
Use only rows where status equals validated; unit must equal count; exclude rows where sensitive_flag is true.
Output
A table sorted by group, with the number of rows used and excluded; charts must label the unit and the time period.
Verification
Attach the filter code you actually used, plus the row counts before and after filtering, so I can re-run and check it.
Code that maps directly to the prompt above
mask = (df["unit"] == "count") & (df["status"] == "validated") & (~df["sensitive_flag"])
filtered = df[mask]

print("Rows before filter:", len(df), "Rows after filter:", len(filtered))

monthly = filtered.groupby(["group", filtered["period"].dt.to_period("M")])["value"].mean()
monthly.sort_values(ascending=False).head()
The five parts of a verifiable prompt
PartQuestion it answers
TaskWhat exactly should be done, using which columns and which metric?
ContextWhat is the data's schema, grain, and version relationship?
RequirementsWhat filters, unit constraints, or forbidden operations apply?
OutputWhat format, and what supporting evidence should the output include?
VerificationWhat should be attached so someone else can re-run and check it?
The same task, with and without verification

A prompt without verification gets back only "Group unit_b has the highest case volume, averaging 112," with nobody knowing how that number was produced. Adding a verification requirement gets back "480 rows before filtering, 365 after, with the code below," letting you re-run the same filter and check whether 112 actually holds up.

  • Does Task state clearly which column and which metric to use?
  • Does Context cover the schema, grain, and version relationships?
  • Do Requirements spell out the filter conditions and forbidden operations?
  • Does Verification require the code and the before/after row counts to be attached?

Warning

Without a verification part, what you get back is usually just a conclusion and a chart, with no re-runnable filter conditions or row counts, making it hard to judge afterward whether the result is trustworthy.
Check yourself

Which prompt change most improves the verifiability of an analysis result?

Which prompt change most improves the verifiability of an analysis result?

Key takeaway: Completing the steps is not enough; the result must be verifiable, reproducible, and explainable.

AI-Generated Python: Read Before Run

40 min

AI-Generated Python: Read Before Run

Learning goal: review imports, columns, filters, joins, formulas, side effects, and expected outputs before execution.

A colleague receives a block of AI-generated code that looks professional and runs it right away. It finishes with no error message, so the output goes straight into a report. Three days later, someone discovers the join used the wrong key, silently double-counting some groups' data. Read before run means: before pressing execute, work through a checklist of what the code is actually going to do, rather than waiting for the result and tracing the problem backward.

Example: AI-generated code that looks fine but hides a risk
import pandas as pd

df = pd.read_csv("DS202_Analysis_Package_Clean.csv")
volume = df[df["unit"] == "count"][["group", "period", "value"]].rename(columns={"value": "volume"})
cost = df[df["unit"] == "usd"][["group", "period", "value"]].rename(columns={"value": "cost"})

# This join uses only "group" as the key and forgets to also match on "period",
# so every row for a group gets paired with every other month for that group
merged = volume.merge(cost, on="group")

merged.to_csv("output_summary.csv")  # side effect: overwrites an existing file
print(len(volume), len(cost), len(merged))  # merged has far more rows than volume or cost alone
The pre-execution checklist
Check itemQuestion to ask
ImportsAre the imported packages reasonable? Any unexpected network calls or unknown sources?
ColumnsDo the referenced column names exist, with the expected type?
FiltersDo the filter conditions match the analysis need (for example, excluding drafts, excluding sensitive_flag rows)?
JoinsIs the join key truly unique, or does the relationship match what you expect? Could it duplicate rows?
FormulaDoes the aggregation or calculation match the definition (for example, does an average mix different units)?
Side effectsDoes the code write, overwrite, or delete an existing file? Is that expected?
Expected outputBefore running, can you already guess a rough expected range, to check against afterward?
Applying the checklist to the code above

Applying the checklist reveals: the join uses only group as the key and never also matches on period, so every month for a group gets paired against every other month; the code also has a side effect, overwriting output_summary.csv. Neither issue will ever make Python raise an error, yet together they are enough to make the whole analysis meaningless.

  • Do the column names and types this code uses actually exist and match expectations?
  • Do the filter conditions truly correspond to the business rule you need?
  • Is the join key unique in the source data? Could it duplicate rows?
  • Does the code write to or overwrite an existing file? Is that what you expected?

Warning

"No error message appeared" does not mean the code does what you wanted. A non-unique join key, a missing filter, or mixed units will never make Python raise an error, yet they can make the entire result wrong.
Check yourself

In the pre-execution checklist, "whether a join could duplicate rows" belongs to which check item?

In the pre-execution checklist, "whether a join could duplicate rows" belongs to which check item?

Key takeaway: Completing the steps is not enough; the result must be verifiable, reproducible, and explainable.

Guided Lab: AI Pair Analyst

55 min

Guided Lab: AI Pair Analyst

Learning goal: with instructor guidance, use AI to propose and implement an analysis, then independently verify each critical step.

Info

Practice question: if AI proposed the approach and wrote the entire analysis for you, what steps would you take to prove that analysis is trustworthy, rather than just believing the conclusion?
  1. Supply the data context
    Give AI the schema, grain, unit rules, and forbidden assumptions as the basis for its proposal.
  2. Ask AI to propose and generate code
    Write a task/context/requirements/output/verification prompt and ask AI to propose a method and implement it.
  3. Read before run
    Before executing, check imports, columns, filters, joins, formulas, and side effects one by one.
  4. Independently verify a critical step
    Recompute at least one key number yourself (for example, the filtered row count or one group's average) and confirm it matches AI's output.
  5. Record what still needs human judgment
    List which decisions in this analysis (for example, whether to include draft rows) still need business confirmation rather than being something the code can decide on its own.
The minimum the Guided Lab should include (fill in your own output)
ItemWhat to report
PromptThe task/context/requirements/output/verification prompt you actually used
Read-before-run checkAt least three potential issues you caught before executing
Independent verificationAt least one number you recomputed yourself that matches AI's output
Still needs human judgmentAt least one assumption or decision that needs business confirmation
A common Guided Lab mistake

A learner working through the Guided Lab found that the AI-proposed code ran smoothly and the resulting average "looked reasonable." But they never recomputed a single number themselves, and only when an instructor asked "how do you know this average is correct" did they discover the filter never excluded draft rows, meaning the entire result had to be redone.

  • Judging only whether the conclusion looks reasonable, without recomputing any key number yourself
  • Forgetting to exclude rows where sensitive_flag is true from the analysis
  • Never requiring the prompt to attach before/after row counts, so there is nothing to check afterward
  • Running AI-generated code directly without first reviewing the join and filter logic item by item

Warning

"The AI-written code ran cleanly" does not mean "this analysis is trustworthy." Every key number should be re-computable by you, and every filter and assumption should be written down clearly.

Done

If AI helps write analysis code, check every item yourself: was the data context fully supplied, did the code follow your requirements, and was every key number independently verified. AI can speed up drafting; verification and the conclusion remain a human responsibility.
Check yourself

You finish the Guided Lab and AI's analysis conclusion looks reasonable, but you discover the requirement "exclude rows where sensitive_flag is true" was never actually applied in the code. What is the most appropriate next step?

You finish the Guided Lab and AI's analysis conclusion looks reasonable, but you discover the requirement "exclude rows where sensitive_flag is true" was never actually applied in the code. What is the most appropriate next step?

Key takeaway: Completing the steps is not enough; the result must be verifiable, reproducible, and explainable.

What next?