如何检查 NaN 值
- 2024-12-04 08:56:00
- admin 原创
- 135
问题描述:
float('nan')
表示 NaN(不是数字)。但我该如何检查呢?
解决方案 1:
使用math.isnan
:
>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
解决方案 2:
测试 NaN 的常用方法是看它是否等于其自身:
def isNaN(num):
return num != num
解决方案 3:
numpy.isnan(number)
告诉您是否如此NaN
。
解决方案 4:
这里有三种方法可以测试变量是否为“NaN”。
import pandas as pd
import numpy as np
import math
# For single variable all three libraries return single boolean
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)}}")
输出:
It's pd.isna: True
It's np.isnan: True
It's math.isnan: True
解决方案 5:
编者注:以下时间安排存在缺陷,例如,它们没有考虑姓名查询时间。请参阅评论。
看来检查它是否等于其自身(x != x
)是最快的。
import pandas as pd
import numpy as np
import math
x = float('nan')
%timeit x != x
44.8 ns ± 0.152 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit math.isnan(x)
94.2 ns ± 0.955 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit pd.isna(x)
281 ns ± 5.48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit np.isnan(x)
1.38 µs ± 15.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
解决方案 6:
这是一个与之相关的答案:
符合 IEEE 754 标准的 NaN 实现
+ 例如:python 的 NaN: `float('nan')`, `numpy.nan`...
任何其他对象:字符串或其他(如果遇到则不会引发异常)
按照标准实现的 NaN 是与其自身进行不等式比较时应返回 True 的唯一值:
def is_nan(x):
return (x != x)
以下列举一些例子:
import numpy as np
values = [float('nan'), np.nan, 55, "string", lambda x : x]
for value in values:
print(f"{repr(value):<8} : {is_nan(value)}")
输出:
nan : True
nan : True
55 : False
'string' : False
<function <lambda> at 0x000000000927BF28> : False
解决方案 7:
我实际上刚刚遇到了这个问题,但对我来说,它是在检查 nan、-inf 或 inf。我只是用
if float('-inf') < float(num) < float('inf'):
对于数字来说,这是正确的,对于 nan 和 inf 来说则是错误的,对于字符串或其他类型的东西会引发异常(这可能是一件好事)。此外,这不需要导入任何库,如 math 或 numpy(numpy 太大了,它会使任何编译后的应用程序的大小增加一倍)。
解决方案 8:
数学.isnan()
或者将数字与其自身进行比较。NaN 始终是 != NaN,否则(例如,如果它是一个数字)比较应该成功。
解决方案 9:
好吧,我进入了这篇文章,因为我对该功能遇到了一些问题:
math.isnan()
运行此代码时出现问题:
a = "hello"
math.isnan(a)
它引发了异常。我的解决方案是进行另一次检查:
def is_nan(x):
return isinstance(x, float) and math.isnan(x)
解决方案 10:
如果你停留在 <2.6 版本,没有 numpy,也没有 IEEE 754 支持,那么可以使用另一种方法:
def isNaN(x):
return str(x) == str(1e400*0)
解决方案 11:
比较pd.isna
,math.isnan
以及np.isnan
它们处理不同类型对象的灵活性。
下表显示是否可以使用给定的方法检查对象的类型:
+------------+-----+---------+------+--------+------+
| Method | NaN | numeric | None | string | list |
+------------+-----+---------+------+--------+------+
| pd.isna | yes | yes | yes | yes | yes |
| math.isnan | yes | yes | no | no | no |
| np.isnan | yes | yes | no | no | yes | <-- # will error on mixed type list
+------------+-----+---------+------+--------+------+
pd.isna
检查不同类型缺失值的最灵活的方法。
所有答案均未涵盖 的灵活性pd.isna
。虽然math.isnan
和np.isnan
将返回True
值NaN
,但您无法检查不同类型的对象(如None
或 字符串)。这两种方法都会返回错误,因此检查混合类型的列表会很麻烦。这个 whilepd.isna
很灵活,将为不同类型的返回正确的布尔值:
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: missing_values = [3, None, np.NaN, pd.NA, pd.NaT, '10']
In [4]: pd.isna(missing_values)
Out[4]: array([False, True, True, True, True, False])
解决方案 12:
使用 Python <2.6 我最终得到了
def isNaN(x):
return str(float(x)).lower() == 'nan'
这对我来说适用于 Solaris 5.9 机器上的 python 2.5.1 和 Ubuntu 10 上的 python 2.6.5
解决方案 13:
NaN
我正在从以字符串形式发送的 Web 服务接收数据'Nan'
。但是我的数据中也可能有其他类型的字符串,因此简单的字符串float(value)
可能会引发异常。我使用了以下可接受答案的变体:
def isnan(value):
try:
import math
return math.isnan(float(value))
except:
return False
要求:
isnan('hello') == False
isnan('NaN') == True
isnan(100) == False
isnan(float('nan')) = True
解决方案 14:
判断变量是否为 NaN 或 None 的所有方法:
无类型
In [1]: from numpy import math
In [2]: a = None
In [3]: not a
Out[3]: True
In [4]: len(a or ()) == 0
Out[4]: True
In [5]: a == None
Out[5]: True
In [6]: a is None
Out[6]: True
In [7]: a != a
Out[7]: False
In [9]: math.isnan(a)
Traceback (most recent call last):
File "<ipython-input-9-6d4d8c26d370>", line 1, in <module>
math.isnan(a)
TypeError: a float is required
In [10]: len(a) == 0
Traceback (most recent call last):
File "<ipython-input-10-65b72372873e>", line 1, in <module>
len(a) == 0
TypeError: object of type 'NoneType' has no len()
NaN 类型
In [11]: b = float('nan')
In [12]: b
Out[12]: nan
In [13]: not b
Out[13]: False
In [14]: b != b
Out[14]: True
In [15]: math.isnan(b)
Out[15]: True
解决方案 15:
在 Python 3.6 中,检查字符串值 x math.isnan(x) 和 np.isnan(x) 会引发错误。因此,如果我事先不知道给定值是数字,我就无法检查它是否为 NaN。以下内容似乎解决了这个问题
if str(x)=='nan' and type(x)!='str':
print ('NaN')
else:
print ('non NaN')
解决方案 16:
如何从混合数据类型列表中删除 NaN(浮点)项
如果可迭代对象中有混合类型,则这里有一个不使用 numpy 的解决方案:
from math import isnan
Z = ['a','b', float('NaN'), 'd', float('1.1024')]
[x for x in Z if not (
type(x) == float # let's drop all float values…
and isnan(x) # … but only if they are nan
)]
['a','b','d',1.1024]
短路评估意味着isnan
不会对非“浮点”类型的值进行调用,因为无需评估右侧即可False and (…)
快速评估。False
解决方案 17:
对于 float 类型的 nan
>>> import pandas as pd
>>> value = float(nan)
>>> type(value)
>>> <class 'float'>
>>> pd.isnull(value)
True
>>>
>>> value = 'nan'
>>> type(value)
>>> <class 'str'>
>>> pd.isnull(value)
False
解决方案 18:
现在是 2024 年,我一直在为此苦苦挣扎。根据以上所有建议和评论,我发现:
numpy 返回空白 Excel 电子表格单元格的 nan。nan 是一个浮点数。
为了测试这一点,
if type(activity) == float and np.isnan(activity):
它也可以很好地与 配合使用math.isnan()
。
除非您首先测试 float,否则不能使用 isnan,因为在另一种类型(例如 str)上运行math.isnan
或numpy.isnan
都会引发错误。
解决方案 19:
如果要检查非NaN的值,则对用于标记 NaN 的所有内容进行取反;pandas 有自己专用的函数来标记非 NaN 值。
lst = [1, 2, float('nan')]
m1 = [e == e for e in lst] # [True, True, False]
m2 = [not math.isnan(e) for e in lst] # [True, True, False]
m3 = ~np.isnan(lst) # array([ True, True, False])
m4 = pd.notna(lst) # array([ True, True, False])
如果您想要过滤非 NaN 的值,这尤其有用。对于 ndarray/Series 对象,==
它是矢量化的,因此也可以使用。
s = pd.Series(lst)
arr = np.array(lst)
x = s[s.notna()]
y = s[s==s] # `==` is vectorized
z = arr[~np.isnan(arr)] # array([1., 2.])
assert (x == y).all() and (x == z).all()
解决方案 20:
为了过滤掉空字符串(''
)、None 和NaN
'num_specimen_seen' 列中的值,我们可以使用pd.notna()
pandas 中的函数。
import pandas as pd
import numpy as np
df = pd.DataFrame({
'num_specimen_seen': [10, 2, 1, '', 34, 'aw', np.NaN, 5, '43', np.nan, 'ed', None, '']
})
for idx, row in df.iterrows():
if pd.notna(row['num_specimen_seen']) and row['num_specimen_seen'] != '':
print(idx, row['num_specimen_seen'])
此代码将NaN
在遍历 DataFrame 时跳过“num_specimen_seen”列中的空字符串。
解决方案 21:
对于 panda 中的字符串,采用 pd.isnull:
if not pd.isnull(atext):
for word in nltk.word_tokenize(atext):
作为 NLTK 的特征提取函数
def act_features(atext):
features = {}
if not pd.isnull(atext):
for word in nltk.word_tokenize(atext):
if word not in default_stopwords:
features['cont({})'.format(word.lower())]=True
return features