1

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.

Melanie
  • 109
  • 1
  • 9
  • Could you expand the one line return function into a normal one, this would really help with legibility. And could you explain what a masked array is supposed to be? – Herman Nov 17 '21 at 14:55
  • @Herman the masked array is a three dimensional array in which some elements are masked based on the corresponding z values. Does that answer your question? Sorry i'm not very good at posing questions. – Melanie Nov 17 '21 at 15:03
  • @hpaulj Do you see what i'm doing wrong? – Melanie Nov 17 '21 at 15:41

1 Answers1

1

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.

sams-studio
  • 631
  • 3
  • 10
  • yes thank you! And yes you fixed the way the function was written. I removed some unnecessary information from it and forgot that. Do you know if there is a way to merge more than 2 masked arrays using np.logical? – Melanie Nov 17 '21 at 15:54
  • Using `np.logical` I don't know, but the same happens if you simply multiply the boolean arrays: `masked_array1_1.mask*masked_array1_2.mask*masked_array1_3.mask` etc. – sams-studio Nov 17 '21 at 15:58
  • https://stackoverflow.com/questions/20528328/numpy-logical-or-for-more-than-two-arguments this actually answered that exact question. Thanks again. – Melanie Nov 17 '21 at 15:59