Sunday, November 17, 2024
Google search engine
HomeLanguagesPython | Pandas Index.fillna()

Python | Pandas Index.fillna()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.fillna() function fill NA/NaN values with the specified value. It only takes a scalar value to be filled for all the missing values present in the Index. The function returns a new object having the missing values filled by the passed value.
 

Syntax: Index.fillna(value=None, downcast=None)
Parameters : 
value : Scalar value to use to fill holes (e.g. 0). This value cannot be a list-likes. 
downcast : a dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible)
Returns : filled : %(klass)s
 

Example #1: Use Index.fillna() function to fill all the missing values in the Index.
 

Python3




# importing pandas as pd
import pandas as pd
 
# Creating the Index
idx = pd.Index([1, 2, 3, 4, 5, None, 7, 8, 9, None])
 
# Print the Index
idx


Output : 
 

Let’s fill all the missing values in the Index with -1. 
 

Python3




# fill na values with -1
idx.fillna(-1)


Output : 
 

As we can see in the output, the Index.fillna() function has filled all the missing values with -1. The function only takes scalar value. 
  
Example #2: Use Index.fillna() function to fill all the missing strings in the Index.
 

Python3




# importing pandas as pd
import pandas as pd
 
# Creating the Index
idx = pd.Index(['Labrador', 'Beagle', None, 'Labrador',
             'Lhasa', 'Husky', 'Beagle', None, 'Koala'])
 
# Print the Index
idx


Output : 
 

As we can see in the output we are having some missing values. For the purpose of data analysis, we would like to fill these missing values with some other indicative values which serves our purpose.
 

Python3




# Fill the missing values by 'Value_Missing'
idx.fillna('Value_Missing')


Output : 
 

As we can see in the output, all the missing strings in the Index has been filled with the passed values.
 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments