检查np.nan是否在数组中返回非预期值

时间:2016-03-02 05:49:00

标签: python numpy

为什么数组元素arr[i][j]在等于​​nan时,未被验证为np.nan?

我已经使用变量进行了一些测试,并且无法找到为什么会出现这种情况。

In : nval
Out: array([  0.,  nan])

In : type(nval)
Out: numpy.ndarray

In : type(nval[0])
Out: numpy.float64

In : type(nval[1])
Out: numpy.float64

In : arr[15][4] 
Out: nan

In : type(arr[15][4])
Out: numpy.float64
# Expected True
In : arr[15][4] == np.nan
Out: False

# Expected True
In:  nval[1] == np.nan
Out: False

# Expected True    
In:  arr[15][4] == nval[1]
Out: False

# Expected True
In:  arr[15][4] in nval
Out: False

In:  0 in nval
Out: True

# Expected True    
In:  np.nan in nval
Out: False

我认为所有人都因同样的原因而失败,只是无法弄清楚在哪里。

代码:

import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt

def spill(arr, nval=[0,np.nan], metric=1):
    m=metric
    narr=np.copy(arr)
    nval=np.asarray(nval)
    for i in range(arr.shape[0]):
        for j in range(arr.shape[1]):
            if arr[i][j] not in nval:
                # This helps to check what is happening
                # print "{0},{1}: {2}".format(i,j,arr[i][j])
                # print narr[i-m:i+m+1:1,j-m:j+m+1:1]
                narr[i-m:i+m+1:1,j-m:j+m+1:1]=arr[i][j]                    
    return narr


msize=50
rrange=10
jump=10
start=5
dpi=96
h=500
w=500

X,Y=np.meshgrid(range(0,msize),range(0,msize))
dat=np.random.rand(msize,msize)*rrange


msk=np.zeros_like(dat)
msk[start::jump,start::jump].fill(1)
mdat=msk*dat
mdat[mdat==0]=np.nan

# If I run spill over the `mdat` before the np.nan, all works fine
# as expected by the tests above. But I wish to be able to check
# also against `np.nan`.
sdat = spill(mdat)

mmdat = ma.masked_where(np.isnan(mdat),mdat)
smdat = ma.masked_where(np.isnan(sdat),sdat)

print mmdat[5]
# I expected similar output except smdat[5][4] and smdat[5][6] should
# be equal to smdat[5][5].
print smdat[5]

1 个答案:

答案 0 :(得分:2)

根据documentation

尝试使用np.isnan