Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over numpy.ma array, ignoring masked values

I would like to iterate over only unmasked values in a np.ma.ndarray.

With the following:

import numpy as np
a = np.ma.array([1, 2, 3], mask = [0, 1, 0])
for i in a:
    print i

I get:

1
--
3

I would like to get the following:

1
3

It seems like np.nditer() may be the way to go, but I don't find any flags that might specify this. How might I do this? Thanks!

like image 370
ryanjdillon Avatar asked Jun 05 '15 16:06

ryanjdillon


People also ask

Can you iterate through Numpy array?

Iterating Arrays Iterating means going through elements one by one. As we deal with multi-dimensional arrays in numpy, we can do this using basic for loop of python. If we iterate on a 1-D array it will go through each element one by one.

How do I access the masked array?

Accessing the maskgetmask(x) outputs the mask of x if x is a masked array, and the special value nomask otherwise. getmaskarray(x) outputs the mask of x if x is a masked array. If x has no invalid entry or is not a masked array, the function outputs a boolean array of False with as many elements as x .

What is Ndenumerate in Python?

ndenumerate(arr)[source] Multidimensional index iterator. Return an iterator yielding pairs of array coordinates and values.


1 Answers

you want to use a.compressed()

import numpy as np
a = np.ma.array([1, 2, 3], mask = [0, 1, 0])
for i in a.compressed():
    print i

which gives:

1
3
like image 78
tmdavison Avatar answered Oct 22 '22 14:10

tmdavison