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

Angus McMorland amcmorl@gmail....
Tue Jul 14 14:47:48 CDT 2009


2009/7/14 Greg Fiske <gfiske@whrc.org>:
> 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])

Using scipy as well, you could use nans and the nanmean function:

import scipy.stats
both = np.vstack((a, b)).astype(float)
both[both == 99] = np.nan
scipy.stats.nanmean(both, axis=0)

-> array([ 2.,  6.,  3.,  8.])

-- 
AJC McMorland
Post-doctoral research fellow
Neurobiology, University of Pittsburgh


More information about the NumPy-Discussion mailing list