Show
How to check if a single value is NaN in python. There are approaches are using libraries (pandas, math and numpy) and without using libraries.NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results. Finding and dealing with NaN within an array, series or dataframe is easy. However, identifying a stand alone NaN value is tricky. In this article I explain five methods to deal with NaN in python. The first three methods involves in-built functions from libraries. The last two relies on properties of NaN for finding NaN values. Method 1: Using Pandas Libraryisna() in pandas library can be used to check if the value is null/NaN. It will return True if the value is NaN/null. import pandas as pd Method 2: Using Numpy Libraryisnan() in numpy library can be used to check if the value is null/NaN. It is similar to isna() in pandas. import numpy as np Method 3: Using math libraryMath library provides has built-in mathematical functions. The library is applicable to all real numbers.
cmath library can be used if dealing with complex numbers. import math Method 4: Comparing with itselfWhen I started my career working with big IT company, I had to undergo a training for the first month. The trainer, when introducing the concept of NaN
values mentioned that they are like aliens we know nothing about. These aliens are constantly shapeshifting, and hence we cannot compare NaN value against itself. def isNaN(num): Method 5: Checking the rangeAnother property of NaN which can be used to check for NaN is the range. All floating point values fall within the range of minus infinity to infinity. infinity < any number< infinity However, NaN values does not come within this range. Hence, NaN can be identified if the value does not fall within the range from minus infinity to infinity. This can be implemented as below: def isNaN(num): I hope you have found the above article helpful. I am sure there would be many other techniques to check for NaN values based on various other logics. Please share the other methods you have come across to check for NaN/ Null values. Cheers! Become a MemberI hope you like the article, I would highly recommend signing up for Medium Membership to read more articles by me or stories by thousands of other
authors on variety of topics. Comparison The table below shows if the type of object can be checked with the given method:
|