Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy: using operator - with arrays containing None

I have a list of numbers which I put into a numpy array:

>>> import numpy as np
>>> v=np.array([10.0, 11.0])

then I want to subtract a number from each value in the array. It can be done like this with numpy arrays:

>>> print v - 1.0
[  9.  10.]

Unfortunately, my data often contains missing values, represented by None. For this kind of data I get this error:

>>> v=np.array([10.0, 11.0, None])
>>> print v - 1.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'

What I would like to get for the above example is:

 [  9.  10.  None]

How can I achieve it in an easy and efficient way?

like image 691
piokuc Avatar asked Feb 13 '13 16:02

piokuc


1 Answers

My recommendation is to either use masked arrays:

v = np.ma.array([10., 11, 0],mask=[0, 0, 1])
print v - 10
>>> [0.0 1.0 --]

or NaNs

v = np.array([10.,11,np.nan])
print v - 10
>>> [  0.   1.  nan]

I actually prefer NaNs as missing data indicators.

like image 125
sega_sai Avatar answered Sep 28 '22 02:09

sega_sai