- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to replace NaN values by Zeroes in a column of a Pandas DataFrame?
To replace NaN values by zeroes or other values in a column of a Pandas DataFrame, we can use df.fillna() method.
Steps
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Use df.fillna(0) to replace NaN in DataFrame with value 0.
Similarly use df.fillna(5) and df.fillna(7) to replace NaN in DataFrame with 5 and 7, respectively.
Print the replaced NaN, DataFrame.
Example
import pandas as pd import numpy as np df = pd.DataFrame( { "x": [5, np.nan, 1, np.nan], "y": [np.nan, 1, np.nan, 10], "z": [np.nan, 1, np.nan, np.nan] } ) print "Input series is:
", df print "After replacing NaN with 0:
", df.fillna(0) print "After replacing NaN with 5:
", df.fillna(5) print "After replacing NaN with 7:
", df.fillna(7)
Output
Input series is: x y z 0 5.0 NaN NaN 1 NaN 1.0 1.0 2 1.0 NaN NaN 3 NaN 10.0 NaN After replacing NaN with 0: x y z 0 5.0 0.0 0.0 1 0.0 1.0 1.0 2 1.0 0.0 0.0 3 0.0 10.0 0.0 After replacing NaN with 5: x y z 0 5.0 5.0 5.0 1 5.0 1.0 1.0 2 1.0 5.0 5.0 3 5.0 10.0 5.0 After replacing NaN with 7: x y z 0 5.0 7.0 7.0 1 7.0 1.0 1.0 2 1.0 7.0 7.0 3 7.0 10.0 7.0
- Related Articles
- How to replace NaN values by Zeroes in a column of a Pandas Series?
- How to count the NaN values in a column in a Python Pandas DataFrame?
- Python Pandas - Replace all NaN elements in a DataFrame with 0s
- Merge Pandas dataframe with a common column and set NaN for unmatched values
- Python - How to Count the NaN Occurrences in a Column in Pandas Dataframe?
- Merge Python Pandas dataframe with a common column and set NaN for unmatched values
- Python - Replace values of a DataFrame with the value of another DataFrame in Pandas
- How to sort a column of a Pandas DataFrame?
- How to check if any value is NaN in a Pandas DataFrame?
- How to shift a column in a Pandas DataFrame?
- Python - Calculate the mean of column values of a Pandas DataFrame
- Python - Calculate the median of column values of a Pandas DataFrame
- Python - Calculate the count of column values of a Pandas DataFrame
- Python - Calculate the maximum of column values of a Pandas DataFrame
- Python - Calculate the minimum of column values of a Pandas DataFrame

Advertisements