
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Replace NaN Values by Zeroes in a Pandas DataFrame Column
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
Advertisements