ChatGPT in data science is most useful for drafting code, explaining errors and suggesting what to check next. The risk is code that runs without an error and still gives a wrong answer. This guide gives you five short Python tests that catch that kind of mistake, whether the code came from ChatGPT, a colleague, an old tutorial or you.
An important note first: we did not run ChatGPT or any other language model for this article. The risky snippets below were written by us to show common failure patterns. They are not model output, and we make no claim about how often any model produces them. Every number comes from running the code with pandas 3.0.5 and scikit-learn 1.9.1.

Where ChatGPT in data science helps
- Turning a plain description into a first draft of pandas, SQL or plotting code.
- Explaining an error message or an unfamiliar function.
- Listing checks or edge cases you may have missed.
- Rewriting a script so it is easier to read.
In each case you stay responsible for the result. Do not paste private or customer data into a chat tool unless your organisation allows it; a few invented rows with the same column names are usually enough to get working code.
Load two small public datasets
import warnings
import numpy as np, pandas as pd
B = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/"
tips = pd.read_csv(B + "tips.csv")
t = pd.read_csv(B + "titanic.csv")Test 1: did the line change anything?
Many older examples fill missing values with inplace=True on a single column. In pandas 3 that no longer updates the table.
df = t.copy()
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
df["age"].fillna(df["age"].median(), inplace=True)
print(df.age.isna().sum(), [x.category.__name__ for x in w])
df["age"] = df["age"].fillna(df["age"].median())
print(df.age.isna().sum())177 ['ChainedAssignmentError']
0After the first version, all 177 ages are still missing. Despite its name, ChainedAssignmentError arrived as a warning, so the script carried on. The test is simple: count the missing values after the fill. Version details matter here, so tell the assistant which pandas version you use. See the pandas copy-on-write guide.
Test 2: how many rows are left?
print(len(t), len(t.dropna()), len(t.dropna(subset=["age", "fare", "sex", "survived"])))
print(t.survived.mean(), t.dropna().survived.mean())891 182 714
0.3838383838383838 0.6758241758241759A bare dropna() keeps 182 of 891 passengers, and the survival rate jumps from 38% to 68% because the rows that remain are not a random sample. Dropping only on the columns you need keeps 714. Print the row count before and after any filter; our missing values guide compares other options.
Test 3: is it the average you meant?
print((tips.tip / tips.total_bill).mean(), tips.tip.sum() / tips.total_bill.sum())0.16080258172250472 0.15153580224410024The first number is the average tip percentage per table (16.1%). The second is the share of all money billed that was tipped (15.2%). Both are correct answers to different questions. Write the question in words before accepting either line.
Test 4: did the join add rows?
Here a small staff table has an accidental duplicate for Sunday.
rate = pd.DataFrame({"day": ["Thur", "Fri", "Sat", "Sun", "Sun"], "staff": [3, 4, 5, 5, 6]})
m = tips.merge(rate, on="day")
print(len(tips), len(m), tips.total_bill.sum(), m.total_bill.sum())
try:
tips.merge(rate, on="day", validate="many_to_one")
except Exception as e:
print(type(e).__name__)244 320 4827.77 6454.93
MergeErrorThe 76 Sunday rows were counted twice, and total billing rose from 4,827.77 to 6,454.93 with no error. Adding validate="many_to_one" turns the silent problem into a MergeError. More in pandas merge and join.
Test 5: does the model learn from pure noise?
This is the most useful test for modelling code. Generate random features and random labels, run the same pipeline, and expect accuracy near 0.5.
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import cross_val_score
r = np.random.default_rng(0)
X = r.normal(size=(100, 2000))
y = r.integers(0, 2, 100)
Xs = SelectKBest(f_classif, k=20).fit_transform(X, y) # selects using all labels
print(cross_val_score(LogisticRegression(), Xs, y, cv=5).mean())
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
print(cross_val_score(pipe, X, y, cv=5).mean())0.78
0.5900000000000001There is nothing to learn, yet the first version reports 0.78 because the features were chosen after seeing the test labels. The pipeline version gives 0.59, much closer to chance; with only 100 rows, some distance from 0.50 is normal noise. The scikit-learn page on common pitfalls explains this leakage, and our cross-validation tutorial shows how to set up folds.
How to ask for code you can test
A vague request gets a vague answer that is harder to check. Give the assistant the column names and types, the library versions, a few invented sample rows and the exact question. For the tip example, “average tip percentage per table” and “share of billed money that was tipped” are different requests, and only you know which one the report needs.
Then ask for the check along with the code: “print the row count before and after every filter and join” or “run this once on random labels and show the score”. You still run it yourself. Text that says a script was tested is not evidence that it was; the output on your own machine is.
Finally, keep what you accept. Save the script in version control, note which parts were drafted with an AI tool if your team asks for that, and turn the checks that matter into assert lines, such as assert len(m) == len(tips) after the join. A check written once keeps working when the data changes next month, long after you have forgotten why you added it.
A review routine for AI-written code
- State your library versions and column types in the prompt.
- Ask for the assumptions the code makes, then check them yourself.
- Print shapes, missing counts and totals before and after each step.
- Compare one group or one row by hand.
- Run modelling code on random labels once.
- Look up unfamiliar arguments in the official documentation.
These checks take a few minutes. They do not prove the analysis is right, and they would not catch a wrong business definition or biased data collection. For the cleaning stage in particular, work through exploratory data analysis before trusting any summary.
Related reading: train test split in Python covers the other common source of over-optimistic scores.
FAQ
Can ChatGPT do data analysis on its own?
Some versions can run code on files you upload, but you still need to check which rows were used, which question was answered and whether the method fits. We did not test those features here.
Will ChatGPT replace data scientists?
We have no data that answers this. What this article shows is that checking results takes knowledge of pandas, statistics and the problem itself.
Is it safe to paste company data into ChatGPT?
Follow your employer’s policy and the provider’s current data terms. When in doubt, use invented sample rows.
What is the quickest check for AI-generated code?
Count rows and missing values before and after. In the examples above that exposes the failed fill, the heavy drop and the duplicated join.
