
- 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 - Mask and replace NaNs with a specific value
To mask and replace NaNs with a specific value, use the index.putmask() method. Within that, set the index.isna() method.
At first, import the required libraries -
import pandas as pd import numpy as np
Creating Pandas index with some NaNs −
index = pd.Index([5, 65, 10, np.nan, 75, np.nan])
Display the Pandas index −
print("Pandas Index...\n",index)
Mask and replace NaN index values with a specific value −
print("\nMask...\n",index.putmask(index.isna(), 111))
Example
Following is the code −
import pandas as pd import numpy as np # Creating Pandas index with some NaNs index = pd.Index([5, 65, 10, np.nan, 75, np.nan]) # 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) # mask and replace NaN index values with a specific value print("\nMask...\n",index.putmask(index.isna(), 111))
Output
This will produce the following output −
Pandas Index... Float64Index([5.0, 65.0, 10.0, nan, 75.0, nan], dtype='float64') Number of elements in the index... 6 Mask... Float64Index([5.0, 65.0, 10.0, 111.0, 75.0, 111.0], dtype='float64')
- Related Articles
- Python - Search DataFrame for a specific value with pandas
- Replace a specific duplicate record with a new value in MySQL
- Python - Replace negative values with latest preceding positive value in Pandas DataFrame
- Python - Replace values of a DataFrame with the value of another DataFrame in Pandas
- Python - Check if the Pandas Index with some NaNs is a floating type
- Replace the empty values from a MySQL table with a specific value
- Python Pandas - Return a new Index of the values set with the mask
- Python Pandas - Insert a new index value at a specific position
- Python Pandas - Check if the index has NaNs
- Python - Density Plots with Pandas for a specific attribute
- Replace array value from a specific position in JavaScript
- Python Pandas - Replace all NaN elements in a DataFrame with 0s
- How to replace characters except last with a mask character in JavaScript?
- Replace only a specific value from a column in MySQL
- Python Pandas - Compute indexer and mask for new index given the current index

Advertisements