user552231
user552231

Reputation: 1135

nanmean of matrix columns in NumPy

I need to take the nanmean of columns in matrix in Python.

For example:

import numpy as np  
a = [[np.nan,2,3,4],[5,np.nan,7,8],[9,10,np.nan,12]] 
a =
matrix([[ nan,   2.,   3.,   4.],
        [  5.,  nan,   7.,   8.],
        [  9.,  10.,  nan,  12.]]) 

The current command returns 6.66.

I would like something like np.nanmean(a) that will return [7,6,5,8].

Upvotes: 3

Views: 1109

Answers (1)

jkalden
jkalden

Reputation: 1588

You need to use the keyword axis=0 to achieve the result!

import numpy as np  
a=[[np.nan,2,3,4],[5,np.nan,7,8],[9,10,np.nan,12]] 

>>> np.nanmean(a, axis=0)
array([ 7.,  6.,  5.,  8.])

See the docs for details.

Omitting the keyword will give the mean of all entries of the matrix that are not np.nan.

Upvotes: 3

Related Questions