在 Python 中檢查 NaN 值
- 
          
            使用 math.isnan()函式檢查 Python 中的nan值
- 
          
            使用 numpy.isnan()函式來檢查 Python 中的nan值
- 
          
            使用 pandas.isna()函式檢查 Python 中的nan值
- 
          
            使用 obj != obj檢查 Python 中的nan值
 
nan 是一個常數,表示給定的值不合法-Not a Number。
注意,nan 和 NULL 是兩個不同的東西。NULL 值表示不存在的東西,是空的。
在 Python 中,我們經常在不同的物件中處理這樣的值。所以有必要檢測這樣的常量。
在 Python 中,我們有 isnan() 函式,它可以檢測 nan 值。而這個函式在兩個模組中可用-NumPy 和 math。pandas 模組中的 isna() 函式也可以檢查 nan 值。
使用 math.isnan() 函式檢查 Python 中的 nan 值
math 庫中的 isnan() 函式可用於檢查浮點物件中的 nan 常數。它對遇到的每一個這樣的值都返回 True。比如說:
import math
import numpy as np
b = math.nan
print(np.isnan(b))
輸出:
True
請注意,math.nan 常量代表一個 nan 值。
使用 numpy.isnan() 函式來檢查 Python 中的 nan 值
numpy.isnan() 函式可以在不同的集合,如列表、陣列等中檢查 nan 值。它檢查每個元素,並在遇到 nan 常量時返回帶有 True 的陣列。例如:
import numpy as np
a = np.array([5, 6, np.NaN])
print(np.isnan(a))
輸出:
[False False  True]
np.NaN() 常量也代表一個 nan 值。
使用 pandas.isna() 函式檢查 Python 中的 nan 值
pandas 模組中的 isna() 函式可以檢測 NULL 或 nan 值。它對所有遇到的此類值返回 True。它還可以檢查 DataFrame 或 Series 物件中的此類值。例如,
import pandas as pd
import numpy as np
ser = pd.Series([5, 6, np.NaN])
print(pd.isna(ser))
輸出:
0    False
1    False
2     True
dtype: bool
使用 obj != obj 檢查 Python 中的 nan 值
對於除 nan 以外的任何物件,表示式 obj == obj 總是返回 True。例如:
print([] == [])
print("1" == "1")
print([1, 2, 3] == [1, 2, 3])
print(float("nan") == float("nan"))
因此,我們可以使用 obj != obj 來檢查值是否為 nan。如果返回值為 True,則為 nan。
import math
b = math.nan
def isNaN(num):
    return num != num
print(isNaN(b))
輸出:
True
然而,這個方法在 Python 的低版本中可能會失敗 (<=Python 2.5)。
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn