float(nan')表示nan(不是数字)。但我该如何检查呢?
当前回答
如何从混合数据类型列表中删除NaN(float)项
如果在可迭代的中有混合类型,这里有一个不使用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]
短路求值意味着不会对非“float”类型的值调用isnan,因为False和(…)很快求值为False,而无需对右侧求值。
其他回答
对于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
numpy.isnan(数字)告诉你它是不是NaN。
math.isnan()
或将数字与自身进行比较。NaN总是!=NaN,否则(例如,如果是数字),比较应成功。
比较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])
使用math.isnan:
>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
推荐文章
- 如何计算线段的法向量?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数
- 滚动或滑动窗口迭代器?
- python的方法找到最大值和它的索引在一个列表?