tags:

views:

662

answers:

4

Hello everybody,

i'm a pretty new user of python and numpy, so i hope my question won't annoy you.

Well, 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.

If anybody can help me that would be great!

PS : sorry for my poor english.

+1  A: 

haven't used numpy, but in standard python you can filter out None using list comprehensions or the filter function

>>> [i for i in [1, 2, None] if i != None]
[1, 2]
>>> filter(lambda x: x != None, [1, 2, None])
[1, 2]

and then average the result to ignore the None

cobbal
+4  A: 

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.

tom10
a member function that helped a lot was `filled`. that brought the masked array back to a normal array, filled with a value that I would recognize as invalid (NaN, -9999, whatever your users need).
mariotomo
+1  A: 

You might also be able to kludge with values like NaN or Inf.

In [1]: array([1, 2, None])
Out[1]: array([1, 2, None], dtype=object)

In [2]: array([1, 2, NaN])
Out[2]: array([  1.,   2.,  NaN])

Actually, it might not even be a kludge. Wikipedia says:

NaNs may also be used to represent missing values in computations.

Actually, this doesn't work for the mean() function, though, so nevermind. :)

In [20]: mean([1, 2, NaN])
Out[20]: nan
endolith
Actually, `mean(a[~isnan(a)])` explicitly choosing all non-NaN values works.
kaizer.se
+1  A: 

You can also use filter, pass None to it, it will filter non True objects, also 0, :D So, use it when you dont need 0 too.

>>> filter(None,[1, 2, None])
[1, 2]
S.Mark