How can I calculate matrix mean values along a matrix, but to remove nan
values from calculation? (For R people, think na.rm = TRUE
).
Here
This is built upon the solution suggested by JoshAdel.
Define the following function:
def nanmean(data, **args):
return numpy.ma.filled(numpy.ma.masked_array(data,numpy.isnan(data)).mean(**args), fill_value=numpy.nan)
Example use:
data = [[0, 1, numpy.nan], [8, 5, 1]]
data = numpy.array(data)
print data
print nanmean(data)
print nanmean(data, axis=0)
print nanmean(data, axis=1)
Will print out:
[[ 0. 1. nan]
[ 8. 5. 1.]]
3.0
[ 4. 3. 1.]
[ 0.5 4.66666667]