Home »
Python »
Python Programs
Efficiently checking if arbitrary object is NaN in NumPy?
Learn, how to check if arbitrary object is NaN or not in Python NumPy?
By Pranit Sharma Last updated : October 09, 2023
NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.
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.
Problem statement
Suppose we are given a NumPy array with some missing values, we need to check if this array contains nan values or not.
Efficiently checking if arbitrary object is NaN
We need to iterate over the data set, I need to detect such missing values and handle them in special ways.
For this purpose, we will use the pandas.isnull() method which will return True if the value is nan and False if the value is not nan.
Let us understand with the help of an example,
Python program for efficiently checking if arbitrary object is NaN in NumPy
# Import pandas
import pandas as pd
# Import numpy
import numpy as np
# Creating a series
s = pd.Series(['A', np.nan, 'B','C',np.nan])
# Display original series
print("Original Series:\n",s,"\n")
# Check for nan
res = pd.isnull(s)
# Display result
print("Result:\n",res)
Output
The output of the above program is:
Python NumPy Programs »