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

user330860 picture user330860 · Jun 7, 2009 · Viewed 30.8k times · Source

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.

Answer

tom10 picture tom10 · Jun 7, 2009

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

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

Unfortunately, masked arrays aren't thoroughly supported in numpy, so you've got to look around to see what can and can't be done with them.