- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 Series?
To replace NaN values by zeroes or other values in a column of Pandas Series, we can use s.fillna() method.
Steps
Create a one-dimensional ndarray with axis labels (including time series).
Print the input series.
Use s.fillna(0) to replace NaN in the series with value 0.
Similarly, use s.fillna(5) and s.fillna(7) to replace NaN in series with values 5 and 7, respectively.
Print the replaced NaN series.
Example
import pandas as pd import numpy as np s = pd.Series([1, np.nan, 3, np.nan, 3, np.nan, 7, np.nan, 3]) print "Input series is:
", s print "After replacing NaN with 0:
", s.fillna(0) print "After replacing NaN with 5:
", s.fillna(5) print "After replacing NaN with 7:
", s.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
To Continue Learning Please Login
Login with Google