Ask Your Question

Revision history [back]

Hello,

You should remove the values NaN from your list and then use mean. One possibility is using list comprehension

sage: l = [NaN, 0.01, 19, -3, NaN]
sage: clean_list = [x for x in l if x is not NaN]
[0.0100000000000000, 19, -3]
sage: mean(clean_list)
5.33666666666667

An other is to use filter

sage: clean_list2 = filter(lambda x: x is not NaN, l)
sage: print clean_list2
[0.0100000000000000, 19, -3]
sage: mean(clean_list2)
5.33666666666667

Perhaps you noticed that I used "is not" instead of "!=". The fact is that the test is a little bit faster as it compares addresses in memory and not the two objects. But this is just a detail.

Best, Vincent

Hello,

You should remove the values NaN from your list and then use mean. One possibility It is using list comprehensiona bit tricky, because of the following behavior

sage: float(NaN) == float(NaN)
False

The answer may be found here. I reproduce what you want in your case

sage: l = [NaN, 0.01, 19, -3, NaN]
[float(NaN), float(0.01), float(19), float(-3), float(NaN)]
sage: from math import isnan
sage: clean_list = [x for x in l if x is not NaN]
[0.0100000000000000, 19, -3]
isnan(x)]
sage: print clean_list
[0.01, 19.0, -3.0]
sage: mean(clean_list)
5.33666666666667
5.336666666666667

An other is to use filter

sage: clean_list2 = filter(lambda x: x is not NaN, l)
sage: print clean_list2
[0.0100000000000000, 19, -3]
sage: mean(clean_list2)
5.33666666666667

Perhaps you noticed that I used "is not" instead of "!=". The fact is that the test is a little bit faster as it compares addresses in memory and not the two objects. But this is just a detail.

Best, Vincent