Quick answer: The most common Python for data science mistakes are chained assignment, forgetting to save a pandas result, comparing with NaN using ==, using and/or on columns, treating numbers as text, filling every gap with zero, merging on duplicate keys, mixing up day and month, changing a NumPy view by accident, and fitting a scaler before the train/test split.
The worst Python for data science mistakes do not crash. They print a number that looks fine but is wrong. Then a chart, a model or a report is built on it.
Here are ten mistakes that beginners often make. For each one you will see the problem, the reason and the fix. The examples are tiny, so you can check them by hand.
Why Python for data science mistakes are hard to spot
In ordinary programming, a bug often stops the program. In data work, code can run on the wrong rows, the wrong type or the wrong month without any error. These are the Python for data science common errors that cost the most time.
So the best habit is simple: know roughly what the answer should be before you run the code.
Mistakes when changing and filtering data
1. Chained assignment
# Wrong: changes a temporary selection
df[df["marks"] < 35]["result"] = "Fail"
Why it fails: the first bracket creates a new selection. The second bracket changes that selection, not df.
# Right: rows and column in one step
df.loc[df["marks"] < 35, "result"] = "Fail"
Older pandas showed a SettingWithCopyWarning. In pandas 3 this pattern never changes the original table. Learn loc and iloc well and the problem disappears.
2. Forgetting to save the result
import pandas as pd
df = pd.DataFrame({"city": ["Hyd", "Vizag"], "sales": [10, 20]})
df.drop(columns="city")
print(df.columns.tolist()) # ['city', 'sales']
df = df.drop(columns="city")
print(df.columns.tolist()) # ['sales']
Why it fails: drop, rename, sort_values and fillna return a new object by default. Assign it back. Also avoid df["sales"].fillna(0, inplace=True). Write df["sales"] = df["sales"].fillna(0), which works the same way in every version.
3. Checking NaN with ==
import numpy as np
import pandas as pd
s = pd.Series([5, np.nan, 7])
print((s == np.nan).sum()) # 0
print(s.isna().sum()) # 1
Why it fails: NaN is not equal to anything, not even itself. Use isna() and notna().
4. Using and/or on columns
# Wrong: ValueError, the truth value of a Series is ambiguous
df[(df["age"] > 20) and (df["marks"] > 60)]
# Right
df[(df["age"] > 20) & (df["marks"] > 60)]
Why it fails: and wants one true or false value. A column has many. Use &, | and ~. Keep the brackets, because & runs before > in Python.
Pro tip: Give each condition a name, such as
adult = df["age"] > 20. Thendf[adult & passed]reads like a sentence, and you can print each condition on its own.
Mistakes with data types and missing values
5. Treating numbers as text
import pandas as pd
s = pd.Series(["100", "20", "3"])
print(s.sort_values().tolist()) # ['100', '20', '3']
print(s.max()) # 3
n = pd.to_numeric(s)
print(n.max()) # 100
Why it fails: text is compared one character at a time, so "3" comes after "100". One stray value such as N/A or 1,200 can turn a whole CSV column into text.
Convert with pd.to_numeric(s, errors="coerce"). Bad values become NaN. Then count those NaN values, because coercing hides the problem if you never look. See fixing data types.
6. Filling every gap with zero
import pandas as pd
age = pd.Series([20, None, 24])
print(age.mean()) # 22.0
print(age.fillna(0).mean()) # 14.666666666666666
Why it fails: a missing age means "we do not know". Zero means "a newborn". The average drops from 22 to under 15.
Ask why the value is missing first. Then choose: drop it, fill it with a median, or keep a flag column. Handling missing values explains the options.
7. Reading dates the wrong way round
import pandas as pd
print(pd.to_datetime("03-04-2027").month) # 3
print(pd.to_datetime("03-04-2027", dayfirst=True).month) # 4
Why it fails: in India, 03-04-2027 means 3 April. By default, pandas reads an unclear date as month first, so it becomes 4 March. Your monthly chart is then wrong with no error.
State the format when you know it: pd.to_datetime(col, format="%d-%m-%Y").
Mistakes when combining and copying data
8. Merging on duplicate keys
import pandas as pd
orders = pd.DataFrame({"cust": [1, 2], "amount": [500, 300]})
people = pd.DataFrame({"cust": [1, 1, 2], "city": ["A", "A", "B"]})
joined = orders.merge(people, on="cust")
print(orders["amount"].sum()) # 800
print(joined["amount"].sum()) # 1300
Why it fails: customer 1 appears twice in people, so the ₹500 order is counted twice.
# Stops with a MergeError if cust repeats in people
orders.merge(people, on="cust", validate="many_to_one")
Compare len(df) before and after every merge. The same trap exists in databases, as our SQL mistakes guide shows.
9. Changing the original through a NumPy view
import numpy as np
raw = np.array([10, 20, 30])
part = raw[:2]
part[0] = 0
print(raw) # [ 0 20 30]
Why it fails: a slice shares memory with the original array. Your "raw" data is now changed. Write raw[:2].copy() when you plan to edit the slice.
Common mistake: In Jupyter, running a cell twice repeats the change. If a cell doubles a column, two runs multiply it by four. Use Restart and Run All before you trust a result.
Mistakes when building models
10. Preparing the data before splitting it
# Wrong: the scaler has already seen the test rows
X_scaled = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y)
Why it fails: this is data leakage. The mean and spread of the test rows affect training, so your score may look better than it should.
# Right: split first, then let a pipeline fit on training data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = make_pipeline(StandardScaler(), LogisticRegression())
model.fit(X_train, y_train)
The same rule applies to filling gaps, selecting features and balancing classes. Anything that learns from data must learn from training data only.
Interview note: Interviewers like to show a scaler before the split and ask, "What is wrong here?" Say the word "leakage", explain it in one sentence and offer a pipeline. More are in our interview questions.
A Python for data science debugging checklist
Use this table when a result looks odd:
| What you see | Check first | Useful code |
|---|---|---|
| Total is too high | Duplicate keys after a merge | df["id"].duplicated().sum() |
| Rows disappeared | Inner join or dropna |
len(df) before and after |
| Max or sort looks wrong | Number stored as text | df.dtypes |
| Average is too low | Zeros used for missing data | (df["x"] == 0).sum() |
| Monthly chart looks strange | Day and month swapped | df["date"].min(), df["date"].max() |
| Score is nearly perfect | Leakage or copied target | List every feature and its source |
| Different result each run | No random seed or old cells | Set random_state, restart and run all |
A simple rule covers most Python for data science beginner mistakes: after each step, print the shape, the types and the missing count.
def check(df, name):
print(name, df.shape, "missing:", int(df.isna().sum().sum()))
print(df.dtypes)
Call check(df, "after merge") between steps. You will usually find the bad step within minutes.
To make these fixes a habit, work through the Python for data science practice problems. To see where cleaning and modelling sit in the full learning path, read the data science course guide.
Frequently asked questions
Why does my pandas code run but not change the DataFrame?
Most pandas methods return a new object, so you must assign the result back. Chained assignment is another cause. Use one loc call with the row condition and column name together.
How do I fix "The truth value of a Series is ambiguous"?
Use & for and, | for or, and ~ for not, with brackets around each condition. Python's normal and/or words need a single True or False, but a column holds many values.
Should I fill missing values with zero?
Only when zero is the true meaning, such as no purchases in a month. A missing age or price is unknown, so zero would distort averages and models.
Why does my table get bigger after a merge?
The key is repeated in both tables, so each match is repeated. Check duplicates in the key column and pass the validate option to merge, so pandas raises an error when the relationship is not what you expect.
How can I debug data science code faster?
Work on five to ten rows whose answer you know by hand. After each step, print the shape, the data types and the number of missing values. The first step that surprises you is usually where the bug is.
Want a trainer to review your notebook? Book a free demo class for the Data Science with AI course. It includes six projects and 5+ interview opportunities through a 60+ company network, subject to the placement policy and eligibility.
