Numpy/Pandas干净的方法来检查特定值是否为NaN [英] Numpy/Pandas clean way to check if a specific value is NaN

查看:82
本文介绍了Numpy/Pandas干净的方法来检查特定值是否为NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查给定值是否为NaN?

How can I check if a given value is NaN?

例如if (a == np.NaN)(无效)

在投票之前,请注意:

  • Numpy的isnan方法引发诸如字符串之类的数据类型错误
  • Pandas文档仅提供删除包含NaN的行的方法,或检查DataFrame是否包含NaN的方法.我在询问是否要检查特定值是否为NaN.
  • 与Stackoverflow相关的问题和Google搜索结果似乎与检查是否有NaN值"或"DataFrame中的哪些值"有关
  • Numpy's isnan method throws errors with data types like string
  • Pandas docs only provide methods to drop rows containing NaNs, or ways to check if/when DataFrame contains NaNs. I'm asking about checking if a specific value is NaN.
  • Relevant Stackoverflow questions and Google search results seem to be about checking "if any value is NaN" or "which values in a DataFrame"

必须有一种干净的方法来检查给定的值是否为NaN?

There must be a clean way to check if a given value is NaN?

推荐答案

您可以使用NaN!= NaN

因此,如果aNaN

这甚至适用于字符串

示例:

In[52]:
s = pd.Series([1, np.NaN, '', 1.0])
s

Out[52]: 
0      1
1    NaN
2       
3      1
dtype: object


for val in s:
    print(val==val)
True
False
True
True

这可以通过向量化的方式完成:

This can be done in a vectorised manner:

In[54]:
s==s

Out[54]: 
0     True
1    False
2     True
3     True
dtype: bool

,但是您仍然可以在整个系列中使用方法isnull:

but you can still use the method isnull on the whole series:

In[55]:
s.isnull()

Out[55]: 
0    False
1     True
2    False
3    False
dtype: bool

更新

如@piRSquared所指出的,如果您比较,它将返回True,但是pd.isnull将返回True,因此根据您是否要将None视为NaN,您仍然可以使用进行比较,如果要将None视为NaN

As noted by @piRSquared if you compare None==None this will return True but pd.isnull will return True so depending on whether you want to treat None as NaN you can still use == for comparison or pd.isnull if you want to treat None as NaN

这篇关于Numpy/Pandas干净的方法来检查特定值是否为NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆