Examples of how to mask/select elements of an array using another array in python
Mask an array from another array
To mask an array, there are several approaches with numpy (see the module called ma). A solution for example is to use numpy.ma.masked_where
to mask the elements of the array x if the elements of the array y are equal to 0, example:
>>> import numpy as np
>>> x = np.array([1,2,3,4])
>>> y = np.array([0,1,1,0])
>>> m = np.ma.masked_where(y==0, x)
>>> m
masked_array(data = [-- 2 3 --],
mask = [ True False False True],
fill_value = 999999)
It is then possible to use the masked_array to compressed x:
>>> masked_x = np.ma.compressed(m)
>>> masked_x
array([2, 3])
Another approach using numpy.ma.getmask:
>>> m_mask = np.ma.getmask(m)
>>> masked_array = np.ma.masked_array(x, mask=m_mask)
>>> masked_x = np.ma.compressed(masked_array)
>>> masked_x
array([2, 3])
Invert the mask
To invert the previous a solution is to use the numpy function invert, example:
>>> m_mask
array([ True, False, False, True])
>>> m_mask = np.invert(m_mask)
>>> m_mask
array([False, True, True, False])
>>> masked_array = np.ma.masked_array(x, mask=m_mask)
>>> np.ma.compressed(masked_array)
array([1, 4])
Mask with multiple conditions
Another example using multiple conditions on y:
>>> import numpy as np
>>> x = np.array([1,2,3,4])
>>> y = np.array(([1,2,3,4],[1,1,1,1]))
>>> m = np.ma.masked_where(((y[0,:]==1)&(y[1,:]==1)), x)
>>> np.ma.compressed(m)
array([2, 3, 4])
Get the opposite mask using the function numpy.ma.masked_not_equal:
>>> x = np.array([1,2,3,4])
>>> y = np.array(([1,2,3,4],[1,1,1,1]))
>>> m = np.ma.masked_not_equal(((y[0,:]==1)&(y[1,:]==1)), x)
>>> mask1 = np.ma.getmask(m)
>>> m = np.ma.masked_array(x, mask=mask1)
>>> np.ma.compressed(m)
array([1])
References
Links | Site |
---|---|
how to apply a mask from one array to another array? | stackoverflow |
The numpy.ma module | docs.scipy.org |
numpy.ma.masked_where | docs.scipy.org |
numpy.ma.masked_equal | docs.scipy.org |
numpy.ma.masked_not_equal | docs.scipy.org |
numpy.ma.masked_object | docs.scipy.org |
numpy.ma.getmask | docs.scipy.org |
numpy.invert | docs.scipy.org |