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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With