float(nan')表示nan(不是数字)。但我该如何检查呢?
当前回答
事实上我刚碰到这个,但对我来说,它是在检查nan、-inf或inf
if float('-inf') < float(num) < float('inf'):
这对于数字是正确的,对于nan和inf都是错误的,对于字符串或其他类型(这可能是一件好事)会引发异常。此外,这不需要导入任何库,如math或numpy(numpy非常大,它的大小是任何编译应用程序的两倍)。
其他回答
用于浮球类型
>>> 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
比较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将为NaN值返回True,但您无法检查None或字符串等不同类型的对象。这两个方法都会返回错误,因此检查混合类型的列表会很麻烦。而pd.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])
判断变量是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
事实上我刚碰到这个,但对我来说,它是在检查nan、-inf或inf
if float('-inf') < float(num) < float('inf'):
这对于数字是正确的,对于nan和inf都是错误的,对于字符串或其他类型(这可能是一件好事)会引发异常。此外,这不需要导入任何库,如math或numpy(numpy非常大,它的大小是任何编译应用程序的两倍)。
在Python 3.6中,检查字符串值x math.isnan(x)和np.issan(x)会引发错误。所以我无法检查给定值是否为NaN,如果我事先不知道它是一个数字。以下内容似乎解决了这个问题
if str(x)=='nan' and type(x)!='str':
print ('NaN')
else:
print ('non NaN')