Replace NaN Values with Zeros in Pandas DataFrame

Imagine opening an Excel sheet and finding some cells completely blank—no number, no text, just emptiness. In pandas, those empty spots are called NaN values (short for Not a Number), and while they might look harmless, they can quietly break your calculations or distort results.

Left unchecked, NaNs can stop you from running simple operations like sums or averages, leading to errors or misleading insights. That’s why learning how to handle them is a crucial step for anyone working with data.

Let’s get started!

Methods to Replace NaN with Zero in Pandas

4.1 Using fillna(0) (Most Common Method)

The quickest way to replace missing values in pandas is with fillna(0). Think of it as telling pandas: “Whenever you see a blank, write zero instead.”

import pandas as pd
import numpy as np

# Sample DataFrame
df = pd.DataFrame({
    "Product": ["A", "B", "C"],
    "Sales": [10, np.nan, 25],
    "Profit": [5, 7, np.nan]
})

print("Original DataFrame:")
print(df)

# Replace NaN with 0
df_filled = df.fillna(0)

print("\nDataFrame after replacing NaN with 0:")
print(df_filled)

Output:

Original DataFrame:
  Product  Sales  Profit
0       A   10.0     5.0
1       B    NaN     7.0
2       C   25.0     NaN

DataFrame after replacing NaN with 0:
  Product  Sales  Profit
0       A   10.0     5.0
1       B    0.0     7.0
2       C   25.0     0.0

Every NaN is now replaced with 0.

Replacing NaN in Specific Columns

Sometimes, you don’t want to replace all NaN values—only those in a specific column. For example, you might want to fill zeros in Sales, but leave Profit as it is.

# Replace NaN only in "Sales" column
df_sales_filled = df.copy()
df_sales_filled["Sales"] = df_sales_filled["Sales"].fillna(0)

print("\nOnly 'Sales' NaN values replaced with 0:")
print(df_sales_filled)

Output:

Only 'Sales' NaN values replaced with 0:
  Product  Sales  Profit
0       A   10.0     5.0
1       B    0.0     7.0
2       C   25.0     NaN

This way, you control exactly where replacements happen.

Using replace() Method

Another option is replace(). The main difference:

  • fillna(0) works only on missing values (NaN).
  • replace() can target any value (including NaN) and replace it.
# Replace NaN with 0 using replace()
df_replaced = df.replace(np.nan, 0)

print("\nUsing replace() to fill NaN with 0:")
print(df_replaced)

Output:

Using replace() to fill NaN with 0:
  Product  Sales  Profit
0       A   10.0     5.0
1       B    0.0     7.0
2       C   25.0     0.0

Both methods give the same result, but replace() is more flexible if you need to handle multiple values beyond NaN.

In-place Replacement vs Creating New DataFrame

By default, pandas creates a new DataFrame when you use fillna() or replace(). If you want to directly modify the original DataFrame (without creating a copy), you can use inplace=True.

Think of it like editing your original Excel sheet vs saving a new file:

  • inplace=False (default) → keeps the original safe and returns a new DataFrame.
  • inplace=True → changes are written directly into the existing DataFrame.
# In-place replacement
df.fillna(0, inplace=True)

print("\nAfter inplace=True, original DataFrame updated:")
print(df)

Output:

After inplace=True, original DataFrame updated:
  Product  Sales  Profit
0       A   10.0     5.0
1       B    0.0     7.0
2       C   25.0     0.0

Now the original DataFrame itself has no NaN values.

3. Why Replace NaN Values with Zeros?

When working with data, you’ll often come across missing values. In pandas, these show up as NaN. Replacing them with zeros can be very practical in certain cases:

  • Numerical datasets where missing means none. For example, if you’re tracking daily sales and a particular day has no sales recorded, it makes sense to treat that as 0 instead of leaving it as NaN.
  • Avoiding errors in calculations. Operations like sum or mean can break or return unexpected results when NaNs are present. Filling them with zeros ensures smooth, predictable calculations.

Think of it like a budget spreadsheet: if you accidentally leave one expense cell blank, your total will be incorrect. Filling that blank with 0 keeps your calculations accurate.

⚠️ A word of caution: while replacing NaN with zero is convenient, it’s not always the right choice. Sometimes, missing values have a different meaning—so blindly filling them with zeros might distort your analysis.

6. When Should You Not Replace NaN with Zeros?

Although replacing NaN values with zeros often makes life easier, there are times when it can misrepresent your data:

  • Survey or feedback data. If someone didn’t answer a question, filling it with 0 may imply a negative response when in reality, it just means “no response.”
  • Sensor or measurement gaps. Missing readings from a sensor shouldn’t automatically be treated as zero, because that might signal no activity rather than no data.

Instead of forcing zeros, you can use alternative strategies:

  • dropna() → remove rows or columns with missing values.
  • fillna(df.mean()) → replace missing values with the column’s mean.
  • fillna(df.median()) → use the median, which is less sensitive to outliers.

These methods preserve the overall structure of your dataset without injecting misleading zeros.

👉 A good rule of thumb: Use zero only when “nothing” truly means zero. For everything else, explore other imputation methods.

Conclusion

In pandas, NaN values represent the “blank spots” in your data, much like empty cells in a spreadsheet. We’ve seen why these missing values matter, how replacing them with zeros can simplify calculations, and the different methods you can use—fillna(0), targeting specific columns, replace(), and even updating your DataFrame in place.

Remember: replacing NaN with zero makes sense in many numerical datasets (like sales or budgets), but it’s not always the right choice for data such as surveys or sensor readings. That’s why it’s important to experiment with different approaches—whether it’s fillna(), dropna(), or filling with a mean or median.

At Syntax Scenarios, we make learning pandas hands-on and practical. Instead of just reading about code, you can try it instantly in our online Python compiler that fully supports pandas. No setup, no installation—just code and learn in real time.

online python compiler with pandas

👉 Give it a try now: copy the examples from this tutorial into our compiler, replace NaN values yourself, and see the results live.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top