IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
18.7 Examples of Using numarray.ma


18.7 Examples of Using numarray.ma


18.7.1 Data with a given value representing missing data

Suppose we have read a one-dimensional list of elements named x. We also know that if any of the values are 1.e20, they represent missing data. We want to compute the average value of the data and the vector of deviations from average.

>>> from numarray.ma import *
>>> x = array([0.,1.,2.,3.,4.])
>>> x[2] = 1.e20
>>> y = masked_values (x, 1.e20)
>>> print average(y)
2.0
>>> print y-average(y)
[ -2.00000000e+00, -1.00000000e+00,  --,  1.00000000e+00,
        2.00000000e+00,]


18.7.2 Filling in the missing data

Suppose now that we wish to print that same data, but with the missing values replaced by the average value.

>>> print filled (y, average(y))


18.7.3 Numerical operations

We can do numerical operations without worrying about missing values, dividing by zero, square roots of negative numbers, etc.

>>> from numarray.ma import *
>>> x=array([1., -1., 3., 4., 5., 6.], mask=[0,0,0,0,1,0])
>>> y=array([1., 2., 0., 4., 5., 6.], mask=[0,0,0,0,0,1])
>>> print sqrt(x/y)
[  1.00000000e+00,  --,  --,  1.00000000e+00, --,  --,]
Note that four values in the result are invalid: one from a negative square root, one from a divide by zero, and two more where the two arrays x and y had invalid data. Since the result was of a real type, the print command printed str(filled(sqrt (x/y))).


18.7.4 Seeing the mask

There are various ways to see the mask. One is to print it directly, the other is to convert to the repr representation, and a third is get the mask itself. Use of getmask is more robust than x.mask(), since it will work (returning None) if x is a numarray array or list.

>>> x = arange(10)
>>> x[3:5] = masked
>>> print x
[0 ,1 ,2 ,-- ,-- ,5 ,6 ,7 ,8 ,9 ,]
>>> print repr(x)
*** Masked array, mask present ***
Data:
[0 ,1 ,2 ,-- ,-- ,5 ,6 ,7 ,8 ,9 ,]
Mask (fill value [0,])
[0,0,0,1,1,0,0,0,0,0,]
>>> print getmask(x)
[0,0,0,1,1,0,0,0,0,0,]


18.7.5 Filling it your way

If we want to print the data with -1's where the elements are masked, we use filled.

>>> print filled(z, -1)
[ 1.,-1.,-1., 1.,-1.,-1.,]


18.7.6 Ignoring extreme values

Suppose we have an array d and we wish to compute the average of the values in d but ignore any data outside the range -100. to 100.

v = masked_outside(d, -100., 100.)
print average(v)


18.7.7 Averaging an entire multidimensional array

The problem with averaging over an entire array is that the average function only reduces one dimension at a time. So to average the entire array, ravel it first.

>>> x
*** Masked array, no mask ***
Data:
[[ 0, 1, 2,]
 [ 3, 4, 5,]
 [ 6, 7, 8,]
 [ 9,10,11,]]
>>> average(x)
*** Masked array, no mask ***
Data:
[ 4.5, 5.5, 6.5,]
>>> average(ravel(x))
5.5

Send comments to the NumArray community.