
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Pandas - Fill NaN values with the specified value in an Index object
To fill NaN values with the specified value in an Index object, use the index.fillna() method in Pandas. At first, import the required libraries −
import pandas as pd import numpy as np
Creating Pandas index with some NaN values as well −
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])
Display the Pandas index −
print("Pandas Index...\n",index)
Fill the NaN with some specific value −
print("\nIndex object after filling NaN value...\n",index.fillna('Amit'))
Example
Following is the code −
import pandas as pd import numpy as np # Creating Pandas index with some NaN values as well index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30]) # Display the Pandas index print("Pandas Index...\n",index) # Return the number of elements in the Index print("\nNumber of elements in the index...\n",index.size) # Return the dtype of the data print("\nThe dtype object...\n",index.dtype) # Fill the NaN with some specific value print("\nIndex object after filling NaN value...\n",index.fillna('Amit'))
Output
This will produce the following output −
Pandas Index... Float64Index([50.0, 10.0, 70.0, nan, 90.0, 50.0, nan, nan, 30.0], dtype='float64') Number of elements in the index... 9 The dtype object... float64 Index object after filling NaN value... Index([50.0, 10.0, 70.0, 'Amit', 90.0, 50.0, 'Amit', 'Amit', 30.0], dtype='object')
- Related Articles
- Python Pandas - Fill missing columns values (NaN) with constant values
- Python Pandas - Fill NaN values using an interpolation method
- Python - How to fill NAN values with mean in Pandas?
- Python Pandas - Return Index without NaN values
- Python Pandas - Fill NaN with Linear Interpolation
- Python Pandas - Fill NaN with Polynomial Interpolation
- Python Pandas - Return a Series containing counts of unique values from Index object considering NaN values as well
- Python Pandas - Drop the value when any level is NaN in a Multi-index
- Python Pandas - Drop the value when all levels are NaN in a Multi-index
- Replace NaN with zero and fill positive infinity values in Python
- Replace NaN with zero and fill negative infinity values in Python
- Python Pandas - Create an Index with values cast to dtypes
- Replace infinity with large finite numbers but fill NaN values in Python
- Python Pandas - Return Index with duplicate values removed
- Python Pandas - Set index name for an already created Index object

Advertisements