Updated answer, April 2025:

pd.to_numeric can convert arguments to a numeric type. The option errors='coerce' sets things to NaN. However, it can only work on 1D objects (i.e. scalar, list, tuple, 1-d array, or Series). Therefore, to use it on a DataFrame, we need to use df.apply to convert each column individually. Note that any **kwargs given to apply will be passed onto the function, so we can still set errors='coerce'.

Using pd.to_numeric along with df.apply will set any strings to NaN. If we want to convert those to 0 values, we can then use .fillna(0) on the resulting DataFrame.

For example (and note this also works with the strings suggested by the original question "$-" and "($24)"):

import pandas as pd

df = pd.DataFrame({
    'a': (1, 'sd', 1),
    'b': (2., 2., 'fg'),
    'c': (4, "$-", "($24)")
    })

print(df)

#     a    b  c
# 0   1  2.0  4
# 1  sd  2.0     $-
# 2   1   fg  ($24)

df = df.apply(pd.to_numeric, errors='coerce').fillna(0)

print(df)

#      a    b  c
# 0  1.0  2.0  4.0
# 1  0.0  2.0  0.0
# 2  1.0  0.0  0.0

My original answer from 2015, which is now deprecated

You can use the convert_objects method of the DataFrame, with convert_numeric=True to change the strings to NaNs

From the docs:

convert_numeric: If True, attempt to coerce to numbers (including strings), with unconvertible values becoming NaN.

In [17]: df
Out[17]: 
    a   b  c
0  1.  2.  4
1  sd  2.  4
2  1.  fg  5

In [18]: df2 = df.convert_objects(convert_numeric=True)

In [19]: df2
Out[19]: 
    a   b  c
0   1   2  4
1 NaN   2  4
2   1 NaN  5

Finally, if you want to convert those NaNs to 0's, you can use df.replace

In [20]: df2.replace('NaN',0)
Out[20]: 
   a  b  c
0  1  2  4
1  0  2  4
2  1  0  5
Answer from tmdavison on Stack Overflow
Top answer
1 of 3
12

Updated answer, April 2025:

pd.to_numeric can convert arguments to a numeric type. The option errors='coerce' sets things to NaN. However, it can only work on 1D objects (i.e. scalar, list, tuple, 1-d array, or Series). Therefore, to use it on a DataFrame, we need to use df.apply to convert each column individually. Note that any **kwargs given to apply will be passed onto the function, so we can still set errors='coerce'.

Using pd.to_numeric along with df.apply will set any strings to NaN. If we want to convert those to 0 values, we can then use .fillna(0) on the resulting DataFrame.

For example (and note this also works with the strings suggested by the original question "$-" and "($24)"):

import pandas as pd

df = pd.DataFrame({
    'a': (1, 'sd', 1),
    'b': (2., 2., 'fg'),
    'c': (4, "$-", "($24)")
    })

print(df)

#     a    b  c
# 0   1  2.0  4
# 1  sd  2.0     $-
# 2   1   fg  ($24)

df = df.apply(pd.to_numeric, errors='coerce').fillna(0)

print(df)

#      a    b  c
# 0  1.0  2.0  4.0
# 1  0.0  2.0  0.0
# 2  1.0  0.0  0.0

My original answer from 2015, which is now deprecated

You can use the convert_objects method of the DataFrame, with convert_numeric=True to change the strings to NaNs

From the docs:

convert_numeric: If True, attempt to coerce to numbers (including strings), with unconvertible values becoming NaN.

In [17]: df
Out[17]: 
    a   b  c
0  1.  2.  4
1  sd  2.  4
2  1.  fg  5

In [18]: df2 = df.convert_objects(convert_numeric=True)

In [19]: df2
Out[19]: 
    a   b  c
0   1   2  4
1 NaN   2  4
2   1 NaN  5

Finally, if you want to convert those NaNs to 0's, you can use df.replace

In [20]: df2.replace('NaN',0)
Out[20]: 
   a  b  c
0  1  2  4
1  0  2  4
2  1  0  5
2 of 3
6

Use .to_numeric to covert the strings to numeric (set strings to NaN using the errors option 'coerce'):

df = pd.to_numeric(df, errors='coerce')

and then convert the NaN value to zeros using replace:

df.replace('NaN',0)
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas replace nan values with zero in a column
Pandas Replace NaN Values with Zero in a Column - Spark By {Examples}
June 26, 2025 - You can use the pandas.DataFrame.fillna() or pandas.DataFrame.replace() methods to replace all NaN or None values in an entire DataFrame with zeros (0).
Discussions

python - Pandas: Replacing Non-numeric cells with 0 - Stack Overflow
I want to replace all non-numeric cells with 0 in pandas. More on stackoverflow.com
🌐 stackoverflow.com
[Pandas] Replacing Zero Values in a Column
First you can find the nonzero mean : nonzero_mean = df[ df.col != 0 ].mean() Then replace the zero values with this mean : df.loc[ df.col == 0, "col" ] = nonzero_mean More on reddit.com
🌐 r/learnpython
2
4
February 20, 2017
python - Pandas: How to replace Zero values in a column with the mean of that column, For all columns with Zero Value - Stack Overflow
Copyfor col in df.columns: val ... df[col].replace(0, val) ... typically iteration is very slow compared to the vectorized array operations that pandas has builtin. 2021-03-19T13:18:21.817Z+00:00 ... Save this answer. ... Show activity on this post. ... Find the answer to your question by asking. Ask question ... See similar questions with these ... More on stackoverflow.com
🌐 stackoverflow.com
python - Pandas: replace empty cell to 0 - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. I have a data frame results that contains empty cells and I would like to replace all empty cells with 0. More on stackoverflow.com
🌐 stackoverflow.com
🌐
InterviewQs
interviewqs.com › ddi-code-snippets › nan-replace-zero
Replace all NaN values with 0's in a column of Pandas dataframe - InterviewQs
A step-by-step Python code example that shows how to replace all NaN values with 0's in a column of Pandas DataFrame. Provided by InterviewQs, a mailing list for coding and data interview problems.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pandas-replace-zeros-with-previous-non-zero-value
Python Pandas: Replace Zeros with Previous Non-Zero Value - GeeksforGeeks
July 23, 2025 - If our data starts with one or more zeros, those cannot be replaced by any preceding value since there is none. We may want to decide on a strategy for handling these cases, such as leaving them as zeros or replacing them with a specific value.
🌐
GeeksforGeeks
geeksforgeeks.org › python › replace-nan-values-with-zeros-in-pandas-dataframe
Replace NaN Values with Zeros in Pandas DataFrame - GeeksforGeeks
# importing libraries import pandas as pd import numpy as np nums = {'Car Model Number': [223, np.nan, 237, 195, np.nan, 575, 110, 313, np.nan, 190, 143, np.nan], 'Engine Number': [4511, np.nan, 7570, 1565, 1450, 3786, 2995, 5345, 7777, 2323, 2785, 1120]} # Create the dataframe df = pd.DataFrame(nums, columns =['Car Model Number']) # Apply the function df['Car Model Number'] = df['Car Model Number'].replace(np.nan, 0) # print the DataFrame df · Output: replace() to replace NaN for a single column · Replace NaN values with zeros for an entire Dataframe using NumPy replace() Syntax to replace NaN values with zeros of the whole Pandas dataframe using replace() function is as follows: Syntax: df.replace(np.nan, 0) Python ·
Published: July 15, 2025
🌐
Syntx Scenarios
syntaxscenarios.com › home › python › replace nan values with zeros in pandas dataframe
Replace NaN Values with Zeros in Pandas DataFrame - Syntax Scenarios
October 3, 2025 - 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.
Find elsewhere
🌐
Erikrood
erikrood.com › Python_References › replace_nan_zero_final.html
Replace all NaN values with 0's in a column of Pandas dataframe
Practice interviewing with a few questions per week. import pandas as pd import numpy as np · raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'], 'age': [20, 19, 22, 21], 'favorite_color': ['blue', 'red', 'yellow', "green"], 'grade': [88, 92, 95, 70]} df = pd.DataFrame(raw_data, index = ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel']) df · #First, we have to create the NaN values df = df.replace(20,np.NaN) df = df.replace(70,np.NaN) df ·
🌐
Python Examples
pythonexamples.org › pandas-dataframe-replace-nan-values-with-zero
How to Replace NaN values with Zero in Pandas DataFrame?
You can replace NaN values with 0 in Pandas DataFrame using DataFrame.fillna() method. Pass zero as argument to fillna() method and call this method on the DataFrame in which you would like to replace NaN values with zero.
🌐
Reddit
reddit.com › r/learnpython › [pandas] replacing zero values in a column
r/learnpython on Reddit: [Pandas] Replacing Zero Values in a Column
February 20, 2017 -

Hi all,

I decided to take my first try at a kaggle competition, however, I've been struggling something for awhile now. Perhaps you can help.

Basically, I've got a dataframe where the latitude and longitude (floats) are both zero for a very very small number of lines.

The std deviation for these columns is tiny, so I was just going to replace the zero values with the mean values. How should I go about this? Nothing I have tried so far has worked.

Thanks.

🌐
AiwithGowtham
aiwithgowtham.in › home › how to replace nan with 0 pandas dataframe
Replace NaN with 0 in Pandas DataFrame: 3 Methods Explained
July 4, 2026 - For a quick zero-fill across the whole DataFrame, df.fillna(0) is always the right answer. If you need to replace NaN values with zeros across an entire DataFrame, you can also use the `fillna()` method. This approach ensures that all NaN values in the DataFrame are handled uniformly: import pandas as pd # Sample DataFrame with NaN values data = { 'A': [1, 2, 3, None, 5], 'B': [None, 2, None, 4, 5], 'C': [1, None, 3, 4, None] } df = pd.DataFrame(data) print("Original DataFrame:") print(df) # Replace NaN values with zeros in the entire DataFrame df = df.fillna(0) print("nDataFrame after replacing all NaN values with zeros:") print(df)
🌐
CodeRivers
coderivers.org › blog › python-replace-specific-element-in-dataframe-with-0
Python: Replacing Specific Elements in a DataFrame with 0 - CodeRivers
February 22, 2026 - In the above code: 1. We first import the pandas library. 2. Create a sample DataFrame with two columns col1 and col2. 3. Use the replace method to replace the value 30 with 0.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.fillna.html
pandas.DataFrame.fillna — pandas 3.0.5 documentation
>>> df.fillna(0) A B C D 0 0.0 2.0 0.0 0.0 1 3.0 4.0 0.0 1.0 2 0.0 0.0 0.0 0.0 3 0.0 3.0 0.0 4.0 · Replace all NaN elements in column ‘A’, ‘B’, ‘C’, and ‘D’, with 0, 1, 2, and 3 respectively.
🌐
w3resource
w3resource.com › python-exercises › pandas › python-pandas-data-frame-exercise-32.php
Pandas: Replace all the NaN values with Zero's in a column of a dataframe - w3resource
September 5, 2025 - Write a Pandas program to fill NaN values with zero across multiple columns using the fillna() method. Write a Pandas program to update a DataFrame column by replacing all NaN entries with zero and then plot a histogram of the column.
🌐
Medium
medium.com › @amit25173 › how-to-fill-nan-values-with-0-in-pandas-a665c5bf9967
How to Fill NaN Values with 0 in Pandas? | by Amit Yadav | Medium
March 6, 2025 - While both methods will give the same result in most cases, fillna(0) is usually the preferred choice for handling missing data in Pandas because it’s optimized for this task. ... Now that you’ve cleaned your dataset, you might want to save it permanently so you don’t have to process it again next time. ... This will save your DataFrame to a CSV file without adding an extra index column.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.replace.html
pandas.DataFrame.replace — pandas 3.0.5 documentation
For a DataFrame a dict can specify that different values should be replaced in different columns. For example, {'a': 1, 'b': 'z'} looks for the value 1 in column ‘a’ and the value ‘z’ in column ‘b’ and replaces these values with whatever is specified in value.