[Numpy-discussion] mean of two or more arrays while ignoring a specific value

David Warde-Farley dwf@cs.toronto....
Tue Jul 14 14:59:01 CDT 2009


On 14-Jul-09, at 3:33 PM, Greg Fiske wrote:

> Dear list,
>
>
>
> I'm learning to work with numpy arrays.  Can somebody explain how to  
> get the
> average of two separate arrays while ignoring a user defined value  
> in one
> array?
>
>
>
> For example:
>
>>>> a = numpy.array([1,5,4,99])
>
>>>> b = numpy.array([3,7,2,8])
>
>
>
> Ignoring the value 99, the result should be an array like c=  
> ([2,6,3,8])


The simplest way I can think of doing it:

In [60]: c = concatenate((a[newaxis,:], b[newaxis,:]),axis=0)

In [61]: c = where(c == 99, nan, float64(c))

In [62]: nansum(c,axis=0) / (~isnan(c)).sum(axis=0)
Out[62]: array([ 2.,  6.,  3.,  8.])

The last line could be replaced with scipy.stats.nanmean(c, axis=0) if  
you have scipy installed.

David



More information about the NumPy-Discussion mailing list