Python Pandas - Replace all NaN elements in a DataFrame with 0s

PythonServer Side ProgrammingProgramming

To replace NaN values, use the fillna() method. Let’s say the following is our CSV file opened in Microsoft Excel with some NaN values −

At first, import the required library −

import pandas as pd

Load data from a CSV file into a Pandas DataFrame −

dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesData.csv")

Replace NaN values with 0s using the fillna() method −

dataFrame.fillna(0)

Example

Following is the code

import pandas as pd

# Load data from a CSV file into a Pandas DataFrame
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesData.csv")
print("DataFrame...
",dataFrame) # replace NaN values with 0s res = dataFrame.fillna(0) print("
DataFrame after replacing NaN values...
",res)

Output

This will produce the following output −

DataFrame...
       Car   Reg_Price   Units
0      BMW        2500   100.0
1    Lexus        3500     NaN
2     Audi        2500   120.0
3   Jaguar        2000     NaN
4  Mustang        2500   110.0

DataFrame after replacing NaN values...
       Car   Reg_Price   Units
0      BMW        2500   100.0
1    Lexus        3500     0.0
2     Audi        2500   120.0
3   Jaguar        2000     0.0
4  Mustang        2500   110.0
raja
Updated on 30-Sep-2021 11:59:22

Advertisements