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,]
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))
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, --, --,]
str(filled(sqrt (x/y)))
.
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,]
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.,]
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)
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.