Home > front end >  merging masked arrays - python
merging masked arrays - python

Time:11-18

Ok i've seen similar questions out there to this and have been trying to apply multiple methods. I can not figure out what i'm doing wrong.

I have a function that creates a masked array:

def masc(arr,z):
        return(np.ma.masked_where((arr[:,:,2] <= z 0.05)*(arr[:,:,2] >= z-0.05)))

where arr is a three dimensional array and z is any value.

I'm working towards iterating this over unique z's, but currently just trialing and erroring running the function with two different z values, and merging the two masked arrays together. The code I have thus far looks like this:

masked_array1_1 = masc(xyz,z1)
masked_array1_2 = masc(xyz,z2)

masked_1 = np.logical_and(masked_array1_1.mask,masked_array1_2.mask)
masked_array1 = np.ma.array(xyz,mask=masked_1)

I get the following error at the line of code

masked_array1 = np.ma.array(xyz,mask = masked_1)

Mask and data not compatible: data size is 703125, mask size is 234375.

I personally feel like the error is plain to see but my weak python eyes can't see it. Let me know if i need to provide example arrays.

CodePudding user response:

First of all, I presume def masc should be like this, right?

def masc(arr,z):
    return np.ma.masked_where((arr[:,:,2] <= z 0.05)*(arr[:,:,2] >= z-0.05), arr[:,:,2])

Now coming back to your question: It's because you have arr[:,:,2] (and not just arr) inside def masc. Suppose xyz has the shape (nx, ny, nz), then the function that's returned by masc has the shape (nx, ny). This does not have the same shape as xyz. You can now either set masked_array1 = np.ma.array(xyz[:,:,2],mask=masked_1) or remove [:,:,2] altogether from everywhere.

  • Related