rh1990
rh1990

Reputation: 940

Deleting masked elements in numpy array

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!

Upvotes: 14

Views: 16684

Answers (2)

Eric
Eric

Reputation: 97601

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

Upvotes: 20

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With mask bitwise invertion ~:

data = data[~data.mask]

Upvotes: 17

Related Questions