How to replace NaN values by Zeroes in a column of a Pandas Dataframe?
You can replace NaN values in a column of a Pandas Dataframe by using the fillna()
method and passing in the value you want to replace NaN with. In this case, you can replace NaN with 0 by using the following code snippet:
import pandas as pd
# Create a sample dataframe
df = pd.DataFrame({'A': [1, 2, 3, 4, 5, float('nan')],
'B': [6, 7, 8, 9, float('nan'), 11],
'C': [12, 13, 14, 15, 16, 17]})
# Replace NaN values in column 'A' with 0
df['A'] = df['A'].fillna(0)
print(df)
Watch a video course
Python - The Practical Guide
You can also replace NaN values in all columns of a Dataframe by using the following code snippet:
df = df.fillna(0)
This will replace NaN values in all columns with 0.