numpy中np.nan(pandas中NAN)

转自:http://blog.csdn.net/xiaodongxiexie/article/details/54352889

在处理数据时遇到NAN值的几率还是比较大的,有的时候需要对数据值是否为nan值做判断,但是如下处理时会出现一个很诡异的结果:

import numpy as np

np.nan == np.nan
#此时会输出为False
  • 1
  • 2
  • 3
  • 4

对np.nan进行help查看,输出如下:

Help on float object:

class float(object)
 |  float(x) -> floating point number
 |  
 |  Convert a string or number to a floating point number, if possible.
 。。。
 |  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

可以得到其属于float的子类,发现有个方法可以这么用:

np.isnan(np.nan)
#这样就可以检测np.nan值了
  • 1
  • 2

或者可以用pandas库来检验:

import pandas as pd
pd.isnull(np.nan)
#此时一样输出为True
#同样的pd.notnull()用来判断不为nan值
  • 1
  • 2
  • 3
  • 4

还可以用python内置math来查看:

In [13]: import math

In [14]: import numpy as np

In [15]: n = np.nan

In [16]: math.isnan(np.nan)
Out[16]: True
原文地址:https://www.cnblogs.com/fengff/p/8295225.html