Remove masked elements from an array

John Machin sjmachin at lexicon.net
Mon Apr 29 20:09:57 EDT 2002


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:

newnums = filter(None, nums)

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

Caveat lector: The OP was talking about a Numeric array. A Numeric
user (i.e. not me) may be able to comment on (a) whether filter()
works on Numeric arrays (b) what the preferred solution is for Numeric
arrays.



More information about the Python-list mailing list