How to Fix Pandas NaN Error in Python
In this tutorial, you'll learn about How to Fix Pandas NaN Error in Python. We cover key concepts, practical examples, and best practices.
Pandas NaN (Not a Number) values cause errors in calculations, comparisons, and filtering when not handled explicitly.
The Wrong Way
import pandas as pd
import numpy as np
data = pd.DataFrame({"A": [1, 2, np.nan, 4], "B": [5, np.nan, 7, 8]})
result = data["A"] + data["B"]
print(result)
Output:
0 6.0
1 NaN
2 NaN
3 12.0
dtype: float64
The NaN values propagate silently, producing unexpected results.
The Right Way
Fill or drop NaN values before calculations:
import pandas as pd
import numpy as np
data = pd.DataFrame({"A": [1, 2, np.nan, 4], "B": [5, np.nan, 7, 8]})
cleaned = data.fillna(0)
result = cleaned["A"] + cleaned["B"]
print(result)
Output:
0 6.0
1 2.0
2 7.0
3 12.0
dtype: float64
Step-by-Step Fix
1. Detect NaN values
print(data.isna())
print(data.isna().sum()) # count NaN per column
print(data.isna().sum().sum()) # total NaN count
2. Drop rows with NaN
data_dropped = data.dropna()
print(data_dropped)
Output:
A B
0 1.0 5.0
3 4.0 8.0
3. Fill NaN with specific values
data_filled = data.fillna({
"A": data["A"].mean(),
"B": data["B"].median()
})
print(data_filled)
4. Use safe comparison
# Wrong -- NaN != NaN returns True
data[data["A"] != data["B"]]
# Right
data[data["A"].notna() & data["B"].notna() & (data["A"] != data["B"])]
5. Use dropna in aggregations
result = data.groupby("A")["B"].mean() # automatically excludes NaN
print(result)
Prevention Tips
- Check for NaN with
data.isna().sum()after loading data. - Use
fillna(),dropna(), orinterpolate()before calculations. - Use
pd.set_option('future.no_silent_downcasting', True)for explicit behavior. - Use
skipna=Trueparameter in aggregation functions. - Use nullable integer types (
pd.Int64Dtype()) to preserve integers with NaN.
Common Mistakes with pandas nan
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro