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)
🌐
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.
Discussions

python - How to replace 0 with None in a pandas column? - Stack Overflow
This seems to be a trivial question but for some reason, I cannot get the code to work. Firstly for the context, column[B] is an object data typed column with 0, "A", "B". A B 0... More on stackoverflow.com
🌐 stackoverflow.com
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 replace multiple columns zero to Nan - Stack Overflow
List with attributes of persons loaded into pandas dataframe df2. For cleanup I want to replace value zero (0 or '0') by np.nan. 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 › 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
🌐
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 ·
Find elsewhere
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.fillna.html
pandas.DataFrame.fillna — pandas 3.0.2 documentation
See more details in the Filling missing data section. ... >>> df = pd.DataFrame( ... [ ... [np.nan, 2, np.nan, 0], ... [3, 4, np.nan, 1], ... [np.nan, np.nan, np.nan, np.nan], ... [np.nan, 3, np.nan, 4], ... ], ... columns=list("ABCD"), ... ) >>> df A B C D 0 NaN 2.0 NaN 0.0 1 3.0 4.0 NaN 1.0 2 NaN NaN NaN NaN 3 NaN 3.0 NaN 4.0 · Replace all NaN elements with 0s.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.replace.html
pandas.DataFrame.replace — pandas 3.0.2 documentation
Note that column names (the top-level dictionary keys in a nested dictionary) cannot be regular expressions. ... This means that the regex argument must be a string, compiled regular expression, or list, dict, ndarray or Series of such elements. If value is also None then this must be a nested dictionary or Series. See the examples section for examples of each of these. ... Value to replace any values matching to_replace with.
🌐
Python Guides
pythonguides.com › pandas-replace-nan-with-0
How To Fill NaN Values With Zeros In Pandas DataFrames
May 21, 2025 - Read Fix “Function Not Implemented for This Dtype” Error in Python · The simplest and most direct way to replace NaN values with zeros is to use the fillna() method in Python: # Replace all NaN values with 0 merged_sales_filled = merged_sales.fillna(0) print(merged_sales_filled)
🌐
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.

🌐
Arab Psychology
scales.arabpsychology.com › home › how to easily replace nan values with zero in pandas using fillna()
How To Easily Replace NaN Values With Zero In Pandas Using Fillna()
December 4, 2025 - The core function driving all these operations is fillna(). By setting the input parameter to 0, we instruct Pandas to replace all instances of NaN found within the specified selection with the integer or float representation of zero.
🌐
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.
🌐
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.
🌐
YouTube
youtube.com › watch
Replace NaN with 0 in pandas DataFrame in Python (2 Examples) | Substitute by Zeros | All/One Column - YouTube
How to exchange NaN values in a pandas DataFrame by 0 in the Python programming language. More details: https://statisticsglobe.com/replace-nan-with-0-in-pan...
Published   January 13, 2023
🌐
GitHub
github.com › pandas-dev › pandas › issues › 20733
Pandas series.str.replace('.0', '') replaces string preceding decimal point · Issue #20733 · pandas-dev/pandas
April 18, 2018 - Code Sample pd.Series(['41.0', '40.0', '35.0', '30.0']).str.replace('.0', '') 0 41 1 2 35 3 dtype: object Problem description Pandas replaces the string preceding '.0' with the string assigned to repl if the preceding string contains a 0...
Author   badebh