🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

AI Assistants in Data Science: Where They Help and Mislead

đŸŸĸ Free Lesson

AI for Data Science

Prerequisites

  • !Python and pandas at the level of groupby and merge
  • !Basic SQL with joins and aggregation
  • !What data leakage means in a train/test split

What You'll Learn

  • 1Decide which data-science tasks are worth delegating to an assistant and which are not
  • 2Prompt for scaffolding code you verify, rather than answers you paste
  • 3Catch dialect, leakage and coercion bugs that assistants introduce with confidence
  • 4Build a small review checklist that turns assistant output into reviewed code

The assistant is a fast junior colleague, not an analyst

Ask an LLM to profile a dataframe and you will get a tidy block that runs, prints histograms, and reports missing values. It will also, roughly one time in five, do something quietly wrong: average an identifier column and present the number without comment, drop rows with inplace=True on a view and mutate the frame you are still using, or compute a "churn rate" whose denominator includes accounts created after the observation window. Nothing in the output flags any of this, because the output was written to look correct, not to be correct.

That is the correct mental model for the tool. An assistant is an extremely fast junior colleague who has read every pandas tutorial and never runs your company's data. It is superb at boilerplate, translation, and enumeration of options; it is unreliable at judgement about your dataset — its column semantics, its date ranges, its known dirty values. The workflow that works treats every generated block as a pull request from someone who will not be around to answer questions: read it, run it on a slice, and check the numbers against something you already know.

Where the hours actually come back

Not every task pays equally. The table below reflects where teams reliably recover time, and where the review cost eats the savings.

TaskWhat to ask forWhat you must verifyTime saved
Boilerplate EDAA profiling function with dtypes, nulls, cardinalityColumn types match the data dictionaryHigh
SQL draftingA query with stated assumptions and a CTE per stepGrain of the join; row count before and afterHigh
Plot selectionThree chart options with the question each answersAxis scale, aggregation level, sample size shownMedium
Feature ideasHypotheses tied to a mechanism, not a wishlistNo future information leaks into the featureMedium
Statistical testsAssumption checks before the test statisticIndependence of observations, multiple-testing planLow to negative
Root-cause analysisAlternative explanations ranked by evidenceWhether the data can distinguish them at allLow

Notice the pattern in the bottom rows: tasks where the hard part is knowing whether the question is well-posed are exactly where an assistant adds fluent text but no judgement. It will happily run a t-test on repeated measures from the same users and hand you a p-value.

Scaffolding an exploration you can re-run

The most reliable pattern is to ask for a function rather than a result. A function can be unit-tested, reviewed once, and re-run as the data changes; a pasted answer decays the moment the extract refreshes.

python
import pandas as pd


def profile_frame(df: pd.DataFrame, id_like: set[str]) -> pd.DataFrame:
    """Column-level profile that refuses to average identifier columns."""
    rows = []
    for col in df.columns:
        s = df[col]
        numeric = pd.api.types.is_numeric_dtype(s)
        is_id = col in id_like or (numeric and s.nunique(dropna=True) == len(s))
        row = {
            "column": col,
            "dtype": str(s.dtype),
            "missing_pct": round(100 * s.isna().mean(), 2),
            "unique": s.nunique(dropna=True),
            "looks_like_id": bool(is_id),
        }
        if numeric and not is_id:
            row["mean"] = round(float(s.mean()), 4)
            row["p50"] = round(float(s.median()), 4)
            row["p99"] = round(float(s.quantile(0.99)), 4)
        rows.append(row)
    return pd.DataFrame(rows)


# Sanity check before trusting any of it: is this the extract you think it is?
raw = pd.read_parquet("events.parquet")
assert raw["event_id"].is_unique, "duplicate events inflate every downstream rate"
print(profile_frame(raw, id_like={"user_id", "order_id", "event_id"}))

Two review questions decide whether this block is safe: does looks_like_id prevent nonsense averages, and does the assertion catch a silently truncated extract? If you cannot answer both, the generated code is decoration.

Drafting SQL without defending a wrong join

For analytical work the assistant is genuinely strong, provided you make the grain explicit in the prompt. Ask for one CTE per conceptual step, an assertion comment at each join, and the dialect you actually run — an assistant that writes DATE_TRUNC and STRING_AGG will not execute on a warehouse that expects date_trunc and LISTAGG, and the error message will not tell you which of your tables is the problem.

-- Weekly active paying accounts, cohort by first paid week.
WITH paid_events AS (
    SELECT user_id, paid_at
      FROM billing_events
     WHERE status = 'captured'          -- excludes refunds and auth holds
),
first_paid AS (
    SELECT user_id, MIN(paid_at) AS first_paid_at
      FROM paid_events
     GROUP BY user_id
),
weekly AS (
    SELECT DATE_TRUNC('week', paid_at) AS week, COUNT(DISTINCT user_id) AS actives
      FROM paid_events
     GROUP BY 1
)
SELECT w.week,
       w.actives,
       COUNT(DISTINCT f.user_id) FILTER (WHERE f.first_paid_at <= w.week) AS cohort_users
  FROM weekly w
  JOIN first_paid f ON f.first_paid_at <= w.week
 GROUP BY w.week, w.actives
 ORDER BY w.week;

Before you trust a generated query, run the three checks that catch most join bugs: count rows before and after each join, confirm the join key's uniqueness on the dimension side, and eyeball whether the date filter is applied before or after the aggregation. An assistant that produces an unbounded fan-out will still print a confident number.

Feature engineering needs a mechanism, not a list

Prompting for "useful features" yields correlation-shaped noise: ratios of columns that share a denominator, rolling means computed over the whole dataset, target encodings fitted before the split. The prompt that works names the mechanism and the leak to avoid — for example, "build a recency feature from days since last order, computed as of each label timestamp, and refuse any feature whose value needs data after that timestamp". Then verify the refusal actually fires:

python
def days_since_last_order(events: pd.DataFrame, labels: pd.DataFrame) -> pd.Series:
    """Recency as of each label timestamp; never looks ahead."""
    events = events.sort_values("ordered_at")
    recency = []
    for uid, t in zip(labels["user_id"], labels["t"]):
        prior = events[(events["user_id"] == uid) & (events["ordered_at"] <= t)]
        last = prior["ordered_at"].max()
        recency.append((t - last).days if pd.notna(last) else 999)
    return pd.Series(recency, index=labels.index, name="days_since_last_order")


def assert_no_lookahead(feature_ts: pd.Series, label_ts: pd.Series) -> None:
    """Fail loudly if any feature was computed from later information."""
    bad = feature_ts[feature_ts > label_ts]
    assert bad.empty, f"{len(bad)} rows use information from after the label timestamp"

The assertion is the deliverable. Code that computes a feature plus code that proves the feature is legal is a reviewable unit; code without the proof is a hypothesis wearing a dataframe's clothes.

Prompt shapes that produce verifiable code

The difference between a usable answer and a decorative one is usually the prompt, and four ingredients account for most of the gap.

Name the artefact. "Write a profiling function with a docstring and a return type" gets reviewed code; "help me explore this data" gets a wall of prose with snippets buried in it. The artefact determines whether your teammate can diff it.

State the contract. Inputs, outputs, dtypes, and what happens on empty data. Assistants handle edge cases surprisingly well when the edge cases are named, and surprisingly poorly when they are implied. Ask explicitly for behaviour on an empty frame, on null keys, and on duplicate rows.

Ban the shortcuts you will pay for. A single line such as "do not use inplace operations, do not coerce dtypes implicitly, do not sample before computing aggregates" removes a cluster of bugs that are cheap to prevent and expensive to notice three weeks later in a dashboard.

Demand the evidence. Ask the model to list its assumptions and the two checks that would falsify them, then run those checks yourself. The list is often incomplete, which is useful information: an assistant that cannot name a failure mode for your dataset has just told you where to look harder.

💡Keep the prompt with the output

Paste the prompt into a notebook cell above the generated block. Six weeks later, when the extract changes shape, the prompt is the only record of what the model was told — and the only way to reproduce a result that suddenly stopped working.

Building a review habit that scales

Make the checklist short enough that people actually run it. Read the code top to bottom before running it. Run it on a fifty-row slice where you know two or three expected values. Compare at least one number against a query you trusted before the assistant existed. Check dtype coercion, timezone handling, and null behaviour explicitly — those are where generated pandas code fails silently rather than loudly. Log the prompt alongside the result in your notebook so a teammate can see what was asked. Finally, keep a running list of the assistant's specific mistakes on your data; that list, not the model's general fluency, is what makes the tool cheaper over time.

Common Mistakes

Accepting a generated aggregate without checking which columns it averaged

Fix: Mark identifier-like columns up front and assert they are excluded from means and sums

Pasting an answer whose SQL dialect does not match your warehouse

Fix: State the engine and version in the prompt and execute a dry run before reviewing numbers

Asking for useful features with no leakage constraint

Fix: Require features computed strictly as of the label timestamp and assert the constraint in code

Delegating test selection and root-cause reasoning

Fix: Keep study design in human hands; use the assistant for drafting and enumeration only

Best Practices

  • Ask for functions and CTEs you can re-run, never for one-shot answers you cannot audit
  • Verify every generated block on a small slice with values you already know
  • Record the prompt next to the output so the reasoning is reviewable later
  • Track your own list of model mistakes on your data — that list is the real productivity gain

Key Takeaways

  • Treat assistant output as a pull request from a fast junior colleague: plausible, fluent, and unverified against your data
  • Delegating a function or a CTE buys reviewable work; pasting a one-shot answer buys decaying text
  • The highest-value prompts name the grain, the dialect, and the leakage constraint explicitly
  • Assertions that prove the code is legal — no look-ahead, no identifier averaging, no fan-out — are part of the deliverable
  • Statistical design and root-cause judgement stay human; boilerplate, drafting and enumeration do not
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement