Search code examples
pythonnumpymean

How to use numpy with 'None' value in Python?


I'd like to calculate the mean of an array in Python in this form:

Matrice = [1, 2, None]

I'd just like to have my None value ignored by the numpy.mean calculation but I can't figure out how to do it.


Solution

  • You are looking for masked arrays. Here's an example.

    import numpy.ma as ma
    a = ma.array([1, 2, None], mask = [0, 0, 1])
    print "average =", ma.average(a)
    

    From the numpy docs linked above, "The numpy.ma module provides a nearly work-alike replacement for numpy that supports data arrays with masks."