Combine two masks with the logical_or operator in Numpy



To combine two masks with the logical_or operator, use the mask_or() method in Python Numpy. If copy parameter is False and one of the inputs is nomask, return a view of the other input mask. Defaults to False. The shrink parameter suggests whether to shrink the output to nomask if all its values are False. Defaults to True. The function returns the result masks values that are masked in either mask1 or mask2. The result may be a view on mask1 or mask2 if the other is nomask (i.e. False).

Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Mask 1 and Mask 2 −

mask1 = np.ma.make_mask([0, 0, 1, 0, 0])
mask2 = np.ma.make_mask([0, 1, 0, 1, 0])

Display the masks −

print("Mask1...
", mask1) print("Mask2...
", mask2)

To combine two masks with the logical_or operator, use the mask_or() method in Python Numpy −

print("
Result...
",np.ma.mask_or(mask1, mask2))

Example

import numpy as np
import numpy.ma as ma

# Masks
mask1 = np.ma.make_mask([0, 0, 1, 0, 0])
mask2 = np.ma.make_mask([0, 1, 0, 1, 0])
print("Mask1...
", mask1) print("Mask2...
", mask2) # To combine two masks with the logical_or operator, use the mask_or() method in Python Numpy print("
Result...
",np.ma.mask_or(mask1, mask2))

Output

Mask1...
[False False True False False]
Mask2...
[False True False True False]
Result...
[False True True True False]

Advertisements