如何检查NaN值

如何检查NaN值

技术背景

在Python编程中,NaN(Not a Number)是一个特殊的浮点数值,通常在数学运算出现未定义结果时产生,如0除以0。在数据处理和分析过程中,经常需要检查数据中是否存在NaN值,以便进行数据清洗和预处理。

实现步骤

1. 使用math.isnan函数

1
2
3
import math
x = float('nan')
print(math.isnan(x)) # 输出: True

2. 利用NaN不等于自身的特性

1
2
3
4
5
def isNaN(num):
return num != num

x = float('nan')
print(isNaN(x)) # 输出: True

3. 使用numpy.isnan函数

1
2
3
import numpy as np
x = float('nan')
print(np.isnan(x)) # 输出: True

4. 使用pandas.isna函数

1
2
3
import pandas as pd
x = float('nan')
print(pd.isna(x)) # 输出: True

核心代码

检查不同类型数据是否为NaN

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import pandas as pd
import numpy as np
import math

# 单个变量检查
x1 = float("nan")
print(f"It's pd.isna: {pd.isna(x1)}")
print(f"It's np.isnan: {np.isnan(x1)}")
print(f"It's math.isnan: {math.isnan(x1)}")

# 检查不同类型数据
values = [float('nan'), np.nan, 55, "string", lambda x: x]
def is_nan(x):
return (x != x)

for value in values:
print(f"{repr(value):<8} : {is_nan(value)}")

过滤列表中的NaN值

1
2
3
4
from math import isnan
Z = ['a', 'b', float('NaN'), 'd', float('1.1024')]
result = [x for x in Z if not (type(x) == float and isnan(x))]
print(result) # 输出: ['a', 'b', 'd', 1.1024]

检查非NaN值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import pandas as pd
import numpy as np
import math

lst = [1, 2, float('nan')]
m1 = [e == e for e in lst]
m2 = [not math.isnan(e) for e in lst]
m3 = ~np.isnan(lst)
m4 = pd.notna(lst)

print(m1) # 输出: [True, True, False]
print(m2) # 输出: [True, True, False]
print(m3) # 输出: array([ True, True, False])
print(m4) # 输出: array([ True, True, False])

最佳实践

灵活处理不同类型数据

如果需要检查不同类型的数据是否为NaN,建议使用pandas.isna函数,它可以处理多种类型的数据,包括None和字符串。

1
2
3
4
5
import pandas as pd
import numpy as np

missing_values = [3, None, np.NaN, pd.NA, pd.NaT, '10']
print(pd.isna(missing_values)) # 输出: array([False, True, True, True, True, False])

避免异常

在使用math.isnannumpy.isnan时,需要先检查数据类型是否为浮点型,以避免抛出异常。

1
2
3
4
5
6
7
import math

def is_nan(x):
return isinstance(x, float) and math.isnan(x)

a = "hello"
print(is_nan(a)) # 输出: False

常见问题

1. 当数据类型不是浮点型时,math.isnannumpy.isnan会抛出异常

解决方法:在调用这两个函数之前,先检查数据类型是否为浮点型。

2. 数据中包含字符串形式的NaN

解决方法:可以使用try-except语句进行处理。

1
2
3
4
5
6
7
8
9
def isnan(value):
try:
import math
return math.isnan(float(value))
except:
return False

print(isnan('hello')) # 输出: False
print(isnan('NaN')) # 输出: True

如何检查NaN值
https://119291.xyz/posts/how-to-check-for-nan-values/
作者
ww
发布于
2025年5月27日
许可协议