Pandas filling NaNs in categorical data

Learn, how can we fill the NaN values in categorical data?
Submitted by Pranit Sharma, on September 14, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Filling NaN values in categorical data

While creating a DataFrame or importing a CSV file, there could be some NaN values in the cells. NaN values mean "Not a Number" which generally means that there are some missing values in the cell.

On the other hand, categorical data is a type of data that has some certain category or characteristic, the value of categorical data is not a single value, rather it consists of classified values, for example, an email can be considered spam or not spam, if we consider 1 as spam and 0 as not spam, we have a classified data in the form of 0 or 1, this is called categorical data.

Let us understand how to fill NaN values in categorical Data.

Python code for filling NaNs in categorical data

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a list
s = ['A','B','C','D',np.nan]

# Creating a Series
se = pd.Series(s,dtype='category')

# Display Series
print("Created Series:\n",se)

# Filling NaN values in this series
result = se.cat.add_categories("E").fillna("E")

# Display result
print("Result:\n",result)

Output:

Example: Pandas filling NaNs in categorical data

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.