I think you need replace by dict:
cols = ["Weight","Height","BootSize","SuitSize","Type"]
df2[cols] = df2[cols].replace({'0':np.nan, 0:np.nan})
Answer from jezrael on Stack Overflow Top answer 1 of 7
122
I think you need replace by dict:
cols = ["Weight","Height","BootSize","SuitSize","Type"]
df2[cols] = df2[cols].replace({'0':np.nan, 0:np.nan})
2 of 7
10
You could use the 'replace' method and pass the values that you want to replace in a list as the first parameter along with the desired one as the second parameter:
cols = ["Weight","Height","BootSize","SuitSize","Type"]
df2[cols] = df2[cols].replace(['0', 0], np.nan)
Statology
statology.org › home › pandas: how to replace zero with nan
Pandas: How to Replace Zero with NaN
October 3, 2022 - import numpy as np #replace all zeros with NaN values df.replace(0, np.nan, inplace=True) #view updated DataFrame print(df) points assists rebounds 0 25.0 5.0 11.0 1 NaN NaN 8.0 2 15.0 7.0 10.0 3 14.0 NaN 6.0 4 19.0 12.0 6.0 5 23.0 9.0 NaN 6 25.0 9.0 9.0 7 29.0 4.0 NaN · Notice that each zero in every column of the DataFrame has been replaced with NaN. Note: We must use the argument inplace=True or else the changes won’t be made to the original DataFrame. Related: How to Replace NaN Values with Zero in Pandas
Can't replace 0 to nan in Python using Pandas - Stack Overflow
I have dataframe with only 1 column. I want to replace all '0' to np.nan but I can't achieve that. More on stackoverflow.com
python - How do I fill NA values in multiple columns in pandas? - Stack Overflow
I have a dataframe with 50 columns. I want to replace NAs with 0 in 10 columns. What's the simplest, most readable way of doing this? I was hoping for something like: cols = ['a', 'b', 'c', 'd... More on stackoverflow.com
python - How to replace NaN values in a dataframe column - Stack Overflow
I have a Pandas Dataframe as below: itm Date Amount 67 420 2012-09-30 00:00:00 65211 68 421 2012-09-09 00:00:00 29424 69 421 2012-09-16 00:00:00 29877 70 421 More on stackoverflow.com
I need to replace NaN in one column with value for other col
I've seen this come up before. You want to use np.where. data['Grade'] = np.where(data['Grade'].isna(),data['Score'],data['Grade']) here's an example that sets null values in grade to values in score, and if it's not null, leaves the current value. More on reddit.com
Videos
01:41
Replacing NaN values with zero in pandas DataFrame in Python - YouTube
04:43
Pandas Change NaN to Zeros in DataFrame - YouTube
02:50
Replace NaN Values by Column Mean of pandas DataFrame in Python ...
04:00
Replace NaN with 0 in pandas DataFrame in Python (2 Examples) | ...
05:41
How to replace NaN with 0 or any value using fillna method in python ...
04:35
[Pandas Tutorial] how to check NaN and replace it (fillna) - YouTube
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.fillna.html
pandas.DataFrame.fillna — pandas 3.0.2 documentation
Replace all NaN elements in column ‘A, ‘B’, ‘C’, and ‘D’, with 0, 1, 2, and 3 respectively.
PythonForBeginners.com
pythonforbeginners.com › home › pandas replace nan with 0 in dataframe
Pandas Replace NaN With 0 in Dataframe - PythonForBeginners.com
January 17, 2023 - You can also replace nan values with 0 in multiple columns using the replace() method. For this, you first need to select the columns where you want to replace the nan values with 0 and invoke the replace() method on the selected columns as shown below. import pandas as pd import numpy as np ...
py4u
py4u.org › blog › python-pandas-replace-multiple-columns-zero-to-nan
Python Pandas: How to Replace Zero (0 or '0') with NaN in Multiple Columns – Fixing the 'astype(str).replace' Not Working Issue
One common task is replacing zeros ... value of 0 might indicate no data was recorded, not actual zero sales). However, many Pandas users struggle with a specific roadblock: the astype(str).replace method fails to reliably replace zeros with NaN, often leading to messy data types or incomplete replacements. In this blog, we’ll demystify why astype(str).replace doesn’t work, explore the right approaches to replace zeros with NaN in multiple columns, and ensure ...
Top answer 1 of 3
24
you can use update():
In [145]: df
Out[145]:
a b c d e
0 NaN NaN NaN 3 8
1 NaN NaN NaN 8 7
2 NaN NaN NaN 2 8
3 NaN NaN NaN 7 4
4 NaN NaN NaN 4 9
5 NaN NaN NaN 1 9
6 NaN NaN NaN 7 7
7 NaN NaN NaN 6 5
8 NaN NaN NaN 0 0
9 NaN NaN NaN 9 5
In [146]: df.update(df[['a','b','c']].fillna(0))
In [147]: df
Out[147]:
a b c d e
0 0.0 0.0 0.0 3 8
1 0.0 0.0 0.0 8 7
2 0.0 0.0 0.0 2 8
3 0.0 0.0 0.0 7 4
4 0.0 0.0 0.0 4 9
5 0.0 0.0 0.0 1 9
6 0.0 0.0 0.0 7 7
7 0.0 0.0 0.0 6 5
8 0.0 0.0 0.0 0 0
9 0.0 0.0 0.0 9 5
2 of 3
11
In [15]: cols= ['one', 'two']
In [16]: df
Out[16]:
one two three four five
a -0.343241 0.453029 -0.895119 bar False
b NaN NaN NaN NaN NaN
c 0.839174 0.229781 -1.244124 bar True
d NaN NaN NaN NaN NaN
e 1.300641 -1.797828 0.495313 bar True
f -0.182505 -1.527464 0.712738 bar False
g NaN NaN NaN NaN NaN
h 0.626568 -0.971003 1.192831 bar True
In [17]: df[cols]=df[cols].fillna(0)
In [18]: df
Out[18]:
one two three four five
a -0.343241 0.453029 -0.895119 bar False
b 0.000000 0.000000 NaN NaN NaN
c 0.839174 0.229781 -1.244124 bar True
d 0.000000 0.000000 NaN NaN NaN
e 1.300641 -1.797828 0.495313 bar True
f -0.182505 -1.527464 0.712738 bar False
g 0.000000 0.000000 NaN NaN NaN
h 0.626568 -0.971003 1.192831 bar True
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.replace.html
pandas.DataFrame.replace — pandas 3.0.2 documentation
You can treat this as a special case of passing two lists except that you are specifying the column to search in. For a DataFrame nested dictionaries, e.g., {'a': {'b': np.nan}}, are read as follows: look in column ‘a’ for the value ‘b’ and replace it with NaN.
Arab Psychology
scales.arabpsychology.com › home › how can i replace all zero values in a pandas dataframe with nan?
How Can I Replace All Zero Values In A Pandas Dataframe With NaN?
June 26, 2024 - import numpy as np #replace all zeros with NaN values df.replace(0, np.nan, inplace=True) #view updated DataFrame print(df) points assists rebounds 0 25.0 5.0 11.0 1 NaN NaN 8.0 2 15.0 7.0 10.0 3 14.0 NaN 6.0 4 19.0 12.0 6.0 5 23.0 9.0 NaN 6 25.0 9.0 9.0 7 29.0 4.0 NaN · Notice that each zero in every column of the DataFrame has been replaced with NaN. Note: We must use the argument inplace=True or else the changes won’t be made to the original DataFrame. ... stats writer (2024). How can I replace all zero values in a Pandas dataframe with NaN?.
Erikrood
erikrood.com › Python_References › replace_nan_zero_final.html
Replace all NaN values with 0's in a column of Pandas dataframe
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 ·
InterviewQs
interviewqs.com › ddi-code-snippets › nan-replace-zero
Replace all NaN values with 0's in a column of Pandas dataframe - InterviewQs
Replace the NaN values in the dataframe (with a 0 in this case) #Now, we can replace them df = df.fillna(0) df
Altcademy
altcademy.com › blog › how-to-replace-nan-with-0-in-pandas
How to replace nan with 0 in Pandas - Altcademy.com
January 12, 2024 - # Replace NaN values with 0 in 'Column1' only df['Column1'] = df['Column1'].fillna(0) # Check the DataFrame now print(df) Now, only the NaN values in 'Column1' have been replaced with zeros, leaving the other columns untouched. What if you want to be a bit more sophisticated with your replacements? For instance, maybe you want to fill in the average sales for days with missing data, rather than just a zero. Pandas has got you covered:
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)
GeeksforGeeks
geeksforgeeks.org › replace-all-the-nan-values-with-zeros-in-a-column-of-a-pandas-dataframe
Replace all the NaN values with Zero's in a column of a Pandas dataframe - GeeksforGeeks
August 25, 2021 - In order to count the NaN values in the DataFrame, we are required to assign a dictionary to the DataFrame and that dictionary should contain numpy.nan values which is a NaN(null) value. Consider the ... Let's explore different methods to replace values in a Pandas DataFrame column based on conditions.
Python Examples
pythonexamples.org › pandas-dataframe-replace-nan-values-with-zero
How to Replace NaN values with Zero in Pandas DataFrame?
Following example program demonstrates how to replace numpy.nan values with 0 for column 'a'. import pandas as pd import numpy as np df = pd.DataFrame( [[np.nan, 72, 67], [23, 78, 62], [32, 74, np.nan], [np.nan, 54, 76]], columns=['a', 'b', 'c']) print('Original DataFrame\n', df) df['a'] = df['a'].fillna(0) print('\nModified DataFrame\n', df)
Top answer 1 of 16
1020
DataFrame.fillna() or Series.fillna() will do this for you.
Example:
In [7]: df
Out[7]:
0 1
0 NaN NaN
1 -0.494375 0.570994
2 NaN NaN
3 1.876360 -0.229738
4 NaN NaN
In [8]: df.fillna(0)
Out[8]:
0 1
0 0.000000 0.000000
1 -0.494375 0.570994
2 0.000000 0.000000
3 1.876360 -0.229738
4 0.000000 0.000000
To fill the NaNs in only one column, select just that column.
In [12]: df[1] = df[1].fillna(0)
In [13]: df
Out[13]:
0 1
0 NaN 0.000000
1 -0.494375 0.570994
2 NaN 0.000000
3 1.876360 -0.229738
4 NaN 0.000000
Or you can use the built in column-specific functionality:
df = df.fillna({1: 0})
2 of 16
200
It is not guaranteed that the slicing returns a view or a copy. You can do
df['column'] = df['column'].fillna(value)