Remove masked elements from an array

holger krekel pyth at devel.trillke.net
Mon Apr 29 20:27:40 EDT 2002


On Mon, Apr 29, 2002 at 05:09:57PM -0700, John Machin wrote:
> holger krekel <pyth at devel.trillke.net> wrote in message news:<mailman.1020102370.5619.python-list at python.org>...
> > On Mon, Apr 29, 2002 at 01:26:25PM -0400, PoulsenL at capecon.com wrote:
> > > I have a Numeric array with missing elements from which I wish to calculate
> > > a histogram.  However, in order to do so I must first remove the 'None'
> > > values from the array.  I have a kludgy solution, but I was wondering if
> > > someone could point me in the right direction on what is the proper method
> > > of collapsing a masked array to just the non-masked values.
> > 
> > there are too solutions. choose yourself :-)
> > 
> > nums = [ 1,2,3,None,2,3]
> > 
> > #version1
> > def f(x): return x is not None
> > newnums = filter(f, nums)
> > 
> > #version2
> > newnums = [ x for x in nums if x is not None]
> > 
> > The first version uses filter. 
> > 'filter' calls 'f' for every item in 'nums' and puts
> > the result into the new list iff it has a 'true' value.
> > 
> > The second version uses list comprehension.
> > It basically does the same if you look closely
> > at it. 
> 
> *Don't* try this if zero is a valid value for your histogram:

i think you are on the wrong track.

the check in question is 'x is not None'. look at it.

> because it will rip out any "false" entries (including 0 or 0.0) that
> you have.

Numbers are always 'not None'. Even 0.000 or 0 or 1-1 or whatever.

>>> nums = [ 1,2,0,3,None,2,3]
>>> print filter(f,nums)
[1, 2, 0, 3, 2, 3]

regards,

    holger





More information about the Python-list mailing list