![]() |
|
[Tut] Check for NaN Values in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Check for NaN Values in Python (/thread-99172.html) |
[Tut] Check for NaN Values in Python - xSicKxBot - 04-09-2022 Check for NaN Values in Python [b]Overview[/b] Problem: How to check if a given value is Code: NaNHere’s a quick look at the solutions to follow: Code: import math
import numpy as np
import pandas as pd x = float('nan')
print(math.isnan(x))
print(x != x)
print(np.isnan(x))
print(pd.isna(x))
print(not(float('-inf') < x < float('inf')))So, what is a Code: NaNCode: NaNCode: NaNCode: NaNWe have to deal with Code: NaN[b]Method 1: Using math.isnan()[/b] The simplest solution to check for NaN values in Python is to use the mathematical function Code: math.isnan()Code: math.isnan()Code: NaNExample: Code: # Importing the math module
import math # Function to check for NaN values
def isNaN(a): # Using math.isnan() if math.isnan(a): print("NaN value encountered!") else: print("Type of Given Value: ", type(a)) # NaN value
x = float('NaN')
isNaN(x)
# Floating value
y = float("5.78")
isNaN(y)Output: Code: NaN value encountered!
Type of Given Value: <class 'float'>In the above example, since Code: xCode: isNaNCode: TrueCode: yCode: isNanCode: FalseCode: y[b]Method 2: Hack NaN Using != Operator[/b] The most unique thing about Code: NaNCode: NaNCode: !=Code: NaNCode: NaNCode: (x == x)Code: TrueCode: NaNExample 1: Code: print(5 == 5)
# True
print(['a', 'b'] == ['a', 'b'])
# True
print([] == [])
# True
print(float("nan") == float("nan"))
# False
print(float("nan") != float("nan"))
# TrueExample 2: Code: # Function to check for NaN values
def not_a_number(x): # Using != operator if x != x: print("Not a Number!") else: print(f'Type of {x} is {type(x)}') # Floating value
x = float("7.8")
not_a_number(x)
# NaN value
y = float("NaN")
not_a_number(y)Output: Code: Type of 7.8 is <class 'float'>
Not a Number!We can also use the Code: NumPyCode: NaNCode: np.isnan(x)The Code: np.isnan(number)Code: NaNExample: In the following example we have a Numpy Array and then we will check the type of each value. We will also check if it is a Code: NaNCode: import numpy as np arr = np.array([10, 20, np.nan, 40, np.nan])
for x in arr: if np.isnan(x): print("Not a Number!") else: print(x, ":", type(x))Output: Code: 10.0 : <class 'numpy.float64'>
20.0 : <class 'numpy.float64'>
Not a Number!
40.0 : <class 'numpy.float64'>
Not a Number! TRIVIALet us try to perform some basic functions on an numpy array that involves Code: NaNCode: import numpy as np arr = np.array([10, 20, np.nan, 40, np.nan])
print(arr.sum())
print(arr.max())Output: Code: nan
nanNow this can be a problem in many cases. So, do we have a way to eliminate the NaN values from our array object and then perform the mathematical operations upon the array elements? Yes! Numpy facilitates us with methods like Code: np.nansum()Code: np.nanmax()Code: NaNExample: Code: import numpy as np arr = np.array([10, 20, np.nan, 40, np.nan])
print(np.nansum(arr))
print(np.nanmax(arr))Output: Code: 70.0
40.0Another way to solve our problem is to use the Code: isna()Code: pandas.isna()Code: NaNExample 1: Code: import pandas as pd x = float("nan")
y = 25.75
print(pd.isna(x))
print(pd.isna(y))Output: Code: True
FalseExample 2: In the following example we will have a look at a Pandas DataFrame and detect the presence of NaN values in the DataFrame. Code: import pandas as pd df = pd.DataFrame([['Mercury', 'Venus', 'Earth'], ['1', float('nan'), '2']])
print(pd.isna(df))Output: Code: 0 1 2
0 False False False
1 False True FalseWe can check for the Code: NaNCode: NaNHence, the idea is to check whether a given value lies within the range of Code: -infCode: infCode: NaNCode: NaNExample: Code: li = [25.87, float('nan')]
for i in li: if float('-inf') < float(i) < float('inf'): print(i) else: print("Not a Number!")Output: Code: 25.87
Not a Number!Recommended read: Python Infinity [b]Conclusion[/b] In this article, we learned how we can use the various methods and modules ( Code: pandasCode: NumPyCode: mathCode: NaNAuthors: SHUBHAM SAYON and RASHI AGARWAL Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)
|