Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

mean

People also ask

What is none in NumPy array?

None is an alias for NP. newaxis. It creates an axis with length 1. This can be useful for matrix multiplcation etc.

Does NumPy mean ignore NaN?

nanmean() function can be used to calculate the mean of array ignoring the NaN value. If array have NaN value and we can find out the mean without effect of NaN value. axis: we can use axis=1 means row wise or axis=0 means column wise.

Is NP A NaN Python?

In Python, NumPy with the latest version where nan is a value only for floating arrays only which stands for not a number and is a numeric data type which is used to represent an undefined value. In Python, NumPy defines NaN as a constant value.


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."


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


You can use scipy for that:

import scipy.stats.stats as st
m=st.nanmean(vec)

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 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