user3601754
user3601754

Reputation: 3862

Python - Combine 2 masks arrays with same dimensions

I would like to combine two masked arrays of same dimensions. I work on a grid and i do calculation on two parts of the array defined with the grid. When i have obtained the 2 masked arrays I want to combine it (sum the 2 results) in a same dimension array...but the masks "annihilate" the results of the other part array.

In other words, i would like to stop the effect of mask when i sum the 2 results.

import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt

#I define the grid and the first masked array
x0 = 3.
y0 = 10.
Lx=20.
Ly=20.

YA, XA = np.mgrid[0:Ly, 0:Lx]


Theta1 = np.arctan((YA-y0)/(XA-x0))

mask = np.fromfunction(lambda i, j: (i >= 0) * (j >= (x0)), (XA.shape[0], XA.shape[1]), dtype='int')
test = np.invert(mask)
test 


V1_test = np.ma.array(Theta1, mask=test)


plt.imshow(V1_test,aspect='auto',cmap=plt.cm.hot,origin="lower")
plt.colorbar()
plt.show()


#The second masked array
Theta2 = np.arctan((YA-y0)/(XA-x0)) + 2*np.pi

mask2 = np.fromfunction(lambda i, j: (i >= 0) * (j < (x0)), (XA.shape[0], XA.shape[1]), dtype='int')
test2 = np.invert(mask2)
test2 


V1_test_2 = np.ma.array(Theta2, mask=test2)


plt.imshow(V1_test_2,aspect='auto',cmap=plt.cm.hot,origin="lower")
plt.colorbar()
plt.show()

#Combine 2 masks arrays
test = V1_test + V1_test_2


plt.imshow(test,aspect='auto',cmap=plt.cm.hot,origin="lower")
plt.colorbar()
plt.show()

Upvotes: 2

Views: 1281

Answers (1)

user707650
user707650

Reputation:

Use numpy.ma.filled:

>>> import numpy as np
>>> data = np.arange(10, 20)
>>> data = np.ma.array(data, mask=np.zeros(data.shape))
>>> data.mask[[3,5,6]] = True
>>> data
masked_array(data = [10 11 12 -- 14 -- -- 17 18 19],
             mask = [False False False  True False  True  True False False False],
       fill_value = 999999)

>>> np.ma.filled(data, 0)
array([10, 11, 12,  0, 14,  0,  0, 17, 18, 19])

Upvotes: 2

Related Questions