Deleting masked elements in numpy array

2020-03-23 14:44发布

问题:

I have some arrays that contain masked elements (from Numpy.MaskedArray), e.g.

data = [0,1,masked,3,masked,5,...]

Where the mask doesn't follow a regular pattern.

I want to iterate through the array and simply delete all elements that are masked to end up with:

data = [0,1,3,5,...]

I've tried a loop like:

for i in xrange(len(data)):
    if np.ma.is_masked(data[i]):
        data.pop(i)

But I get the error: local variable 'data' referenced before assignment

Do I have to create a new array and add the unmasked elements? Or is there a MaskedArray function that can automatically do this? I've had a look at the documentation but it's not obvious to me.

Thanks!

回答1:

With mask bitwise invertion ~:

data = data[~data.mask]


回答2:

data.compressed() is the function you're looking for