NumPy: calculate averages with NaNs removed

前端 未结 12 2503
慢半拍i
慢半拍i 2020-11-27 18:45

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

12条回答
  •  孤城傲影
    2020-11-27 19:34

    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]
    

提交回复
热议问题