
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Pandas - Replace all NaN elements in a DataFrame with 0s
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...\n",dataFrame) # replace NaN values with 0s res = dataFrame.fillna(0) print("\nDataFrame after replacing NaN values...\n",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
- Related Articles
- How to replace NaN values by Zeroes in a column of a Pandas DataFrame?
- Python - Replace values of a DataFrame with the value of another DataFrame in Pandas
- Merge Python Pandas dataframe with a common column and set NaN for unmatched values
- Python - Replace negative values with latest preceding positive value in Pandas DataFrame
- Python - How to Count the NaN Occurrences in a Column in Pandas Dataframe?
- How to count the NaN values in a column in a Python Pandas DataFrame?
- Merge Pandas dataframe with a common column and set NaN for unmatched values
- Python Pandas - Fill NaN with Linear Interpolation
- Python Pandas - Fill NaN with Polynomial Interpolation
- Python Pandas – Display all the column names in a DataFrame
- Python - Summing all the rows of a Pandas Dataframe
- How to check if any value is NaN in a Pandas DataFrame?
- Replace NaN with zero and infinity with large finite numbers in Python
- Replace NaN with zero and fill positive infinity values in Python
- Replace NaN with zero and fill negative infinity values in Python

Advertisements