float('nan')导致Nan(不是数字)。 但我该如何检查呢? 应该很容易,但我找不到它。
有关Python中某些NaN的历史,请参阅PEP 754. python.org/dev/peps/pep-0754
然后numpy.isnan(numpy.nan)将返回True。 很明显,import numpy之前这样做了。:)
math.isnan(x)的
Return True if x is a NaN (not a number), and False otherwise.
1
2
3
4>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
请注意,这与float("nan")一样,与numpy.core.numeric.NaN一样,而将两者与is进行比较则不起作用。因此,这可能是(遗留?)代码中可能包含两个定义的优选解决方案,如果我没有弄错的话?
那里有多种NaN,所以我不知道运营商在那种情况下做了什么?
我上面的代码出错了。是因为python 3吗?然而,numpy.isnan(浮(nan))确实有效。为什么我会使用数学而不是numpy?
@ charlie-parker:在Python3中,math.isnan仍然是数学模块的一部分。 docs.python.org/3/library/math.html#math.isnan。如果你愿意,可以使用numpy.isnan,这个答案只是一个建议。
@gimel我有一个问题。为什么float("nan")在float("string")不工作时有效?
@ SittingBull请参阅docs.python.org/3/library/functions.html#float"如果参数是字符串,则应包含小数"或"Infinity""inf""nan"
注意:仅适用于float;当x是str时抛出TypeError。
是math.isnan优先np.isnan()?
@TMWP可能...... import numpy需要大约15 MB的RAM,而import math大约需要0.2 MB
如果它是一个字符串怎么办?
@Joel:字符串不是数字。根本不应该将字符串传递给此检查。这是对浮点NaN值的检查。此外,isdigit不是数字检查。例如,1.0.isdigit()产生False。
@TMWP:如果你使用NumPy,numpy.isnan是一个更好的选择,因为它处理NumPy数组。如果你没有使用NumPy,那么获取NumPy依赖并花费时间加载NumPy只是为了进行NaN检查没有任何好处(但是如果你编写那种执行NaN检查的代码,那么你可能应该使用NumPy)。
简单地说,没有导入数学:如果x == float(nan)
@jungwook实际上没有用。你的表达总是假的。也就是说,float(nan) == float(nan)返回False - 这是一个奇怪的约定,但基本上是NaN定义的一部分。你想要的方法实际上是由Chris Jester-Young发布的方法,如下所示。
@Mike哦,你说得对。真奇怪。谢谢
测试NaN的常用方法是查看它是否与自身相同:
1
2def isNaN(num):
return num != num
警告:引用Bears评论如下"对于那些被python <= 2.5的人.Nan!= Nan无法可靠地工作。使用numpy代替。"话虽如此,我从未见过它失败过。
我确信,鉴于运算符重载,我有很多方法可以混淆这个函数。和math.isnan()一起去
它在上面提到的754规范中说NaN == NaN应该总是假的,尽管它并不总是如此实现。是不是有可能这就是数学和/或numpy在引擎盖下检查这个怎么样?
谢谢 。如果在标量上进行操作,这也比使用np.isnan快15-20倍
numpy.isnan(number)告诉您它是否是NaN。
谢谢,坚持使用2.5,这正是我所需要的
也适用于python 2.7版本。
如果您需要确定列表中的所有元素是否为nan,那么numpy.all(numpy.isnan(data_list))也很有用
不需要NumPy:all(map(math.isnan, [float("nan")]*5))
当这个答案写于6年前,Python 2.5仍然普遍使用 - 而math.isnan不是标准库的一部分。现在我真的希望在许多地方不是这样的!
如果你使用numpy并且不想导入math,这也很有用。
请注意,np.isnan()不处理decimal.Decimal类型(尽可能多的numpys函数)。 math.isnan()确实处理。
我更喜欢这个接受的答案,因为numpy.isnan可以在math.isnan抛出时处理数组:TypeError: only size-1 arrays can be converted to Python scalars。
我实际上只是碰到了这个,但对我来说,它正在检查nan,-inf或inf。我刚刚用过
1if float('-inf') < float(num) < float('inf'):
这对于数字来说是正确的,对于nan和inf都是假的,并且会对字符串或其他类型(这可能是一件好事)引发异常。此外,这不需要导入任何库,如数学或numpy(numpy是如此的大,它是任何编译的应用程序的大小翻倍)。
math.isfinite直到Python 3.2才被引入,所以鉴于@DaveTheScientist的答案是在2012年发布的,它并不完全"重新发明轮子" - 解决方案仍然代表那些使用Python 2的人。
这是一个回答:
python非唯一NaN:float('nan')
numpy unique NaN(singleton):np.nan
任何其他对象:字符串或其他(遇到异常时不引发异常)
这里是:
1
2
3
4import numpy as np
def is_nan(x):
return (x is np.nan or x != x)
还有一些例子:
1
2
3values = [float('nan'), np.nan, 55,"string", lambda x : x]
for value in values:
print"{:<8} : {}".format(repr(value), is_nan(value))
输出:
1
2
3
4
5nan : True
nan : True
55 : False
'string' : False
at 0x000000000927BF28> : False
系列Im检查是缺少值的字符串是nan??s(???)所以这个解决方案适用于其他人失败的地方。
math.isnan()
或者将数字与自身进行比较。 NaN总是!= NaN,否则(例如,如果它是一个数字),比较应该成功。
对于卡住python <= 2.5的人。 Nan!= Nan没有可靠的工作。用numpy代替。
以下三种方法可以测试变量是否为"NaN"。
1
2
3
4
5
6
7
8
9
10import 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)}")
产量
1
2
3It's pd.isna : True
It's np.isnan : True
It's math.isnan : True
另一种方法,如果你坚持<2.6,你没有numpy,并且你没有IEEE 754支持:
1
2def isNaN(x):
return str(x) == str(1e400*0)
好吧,我输入了这篇文章,因为我的功能存在一些问题:
1math.isnan()
运行此代码时出现问题:
1
2a ="hello"
math.isnan(a)
它引发了例外。
我的解决方案是再次检查:
1
2def is_nan(x):
return isinstance(x, float) and math.isnan(x)
它可能被downvoted,因为isnan()采用浮点数而不是字符串。这个功能没什么问题,问题只在于他试图使用它。 (对于该特定用例,他的解决方案是有效的,但它不是这个问题的答案。)
小心以这种方式检查类型。这不会起作用,例如对于numpy.float32 NaNs。最好使用try / except结构:def is_nan(x): try: return math.isnan(x) except: return False
NaN并不意味着值不是有效数字。它是IEEE浮点表示的一部分,用于指定特定结果未定义。例如0 / 0.因此询问"你好"是否为nan是没有意义的。
这是更好的,因为NaN可以登陆任何字符串,整数或浮点数,所以有用的检查
随着python <2.6,我最终得到了
1
2def isNaN(x):
return str(float(x)).lower() == 'nan'
这适用于Solaris 5.9机器上的python 2.5.1和Ubuntu 10上的python 2.6.5
这太便携了,因为Windows有时称之为-1.#IND
告诉变量是NaN还是None的所有方法:
没有类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29In [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"", line 1, in
math.isnan(a)
TypeError: a float is required
In [10]: len(a) == 0
Traceback (most recent call last):
File"", line 1, in
len(a) == 0
TypeError: object of type 'NoneType' has no len()
NaN型
1
2
3
4
5
6
7
8
9
10
11
12In [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
我从Web服务接收数据,该服务将NaN作为字符串'Nan'发送。但是我的数据中可能还有其他类型的字符串,因此简单的float(value)可能会抛出异常。我使用了以下接受的答案变体:
1
2
3
4
5
6def isnan(value):
try:
import math
return math.isnan(float(value))
except:
return False
需求:
1
2
3
4isnan('hello') == False
isnan('NaN') == True
isnan(100) == False
isnan(float('nan')) = True
或try: int(value)
@chwi所以你的建议是什么告诉value是NaN?
好吧,作为"不是数字",任何无法转换为int的东西我猜其实不是数字,而try语句会失败吗?尝试,返回true,除了返回false。
@chwi嗯,从字面上看"不是数字",你是对的,但这不是重点。事实上,我正在寻找NaN的语义(就像在python中你可以从float(inf) * 0得到的),因此尽管字符串Hello不是数字,但它也不是NaN因为NaN仍然是一个数值!
如何从混合数据类型列表中删除NaN(float)项
如果你在迭代中有混合类型,这里有一个不使用numpy的解决方案:
1
2
3
4
5
6
7
8from 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
)]
1['a', 'b', 'd', 1.1024]
短路评估意味着不会在非浮点类型的值上调用isnan,因为False and (…)快速求值为False而无需评估右侧。
For nan of type float
1
2
3
4
5
6
7
8
9
10
11
12>>> import pandas as pd
>>> value = float(nan)
>>> type(value)
>>>
>>> pd.isnull(value)
True
>>>
>>> value = 'nan'
>>> type(value)
>>>
>>> pd.isnull(value)
False
对于panda中的字符串,请参阅pd.isnull:
1
2if not pd.isnull(atext):
for word in nltk.word_tokenize(atext):
作为NLTK的特征提取功能
1
2
3
4
5
6
7def 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
这减少了什么?