Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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')
Advertisements
