开发者

Numpy masked arrays - indicating missing values

import numpy as np
import num开发者_运维问答py.ma as ma

"""This operates as expected with one value masked"""
a = [0., 1., 1.e20, 9.]
error_value = 1.e20
b = ma.masked_values(a, error_value)
print b

"""This does not, all values are masked """
d = [0., 1., 'NA', 9.]
error_value = 'NA'
e = ma.masked_values(d, error_value)
print e

How can I use 'nan', 'NA', 'None', or some similar value to indicate missing data?


Are you getting your data from a text file or similar? If so, I'd suggest using the genfromtxt function directly to specify your masked value:

In [149]: f = StringIO('0.0, 1.0, NA, 9.0')

In [150]: a = np.genfromtxt(f, delimiter=',', missing_values='NA', usemask=True)

In [151]: a
Out[151]:
masked_array(data = [0.0 1.0 -- 9.0],
             mask = [False False  True False],
       fill_value = 1e+20)

I think the problem in your example is that the python list you're using to initialize the numpy array has heterogeneous types (floats and a string). The values are coerced to a strings in a numpy array, but the masked_values function uses floating point equality yielding the strange results.

Here's one way to overcome this by creating an array with object dtype:

In [152]: d = np.array([0., 1., 'NA', 9.], dtype=object)

In [153]: e = ma.masked_values(d, 'NA')

In [154]: e
Out[154]:
masked_array(data = [0.0 1.0 -- 9.0],
             mask = [False False  True False],
       fill_value = ?)

You may prefer the first solution since the result has a float dtype.


This solution works, it does force the creation of a copy of the array.

a_true = (a == 'NA')

a[a_true] = 1.e20

a = a.astype(float)

print a

error_value = 1.e20

b = ma.masked_values(a, error_value)

print b
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜