Numpy integer nan

PythonNumpyIntegerNan

Python Problem Overview


Is there a way to store NaN in a Numpy array of integers? I get:

a=np.array([1],dtype=long)
a[0]=np.nan

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot convert float NaN to integer

Python Solutions


Solution 1 - Python

No, you can't, at least with current version of NumPy. A nan is a special value for float arrays only.

There are talks about introducing a special bit that would allow non-float arrays to store what in practice would correspond to a nan, but so far (2012/10), it's only talks.

In the meantime, you may want to consider the numpy.ma package: instead of picking an invalid integer like -99999, you could use the special numpy.ma.masked value to represent an invalid value.

a = np.ma.array([1,2,3,4,5], dtype=int)
a[1] = np.ma.masked
masked_array(data = [1 -- 3 4 5],
             mask = [False  True False False False],
       fill_value = 999999)

Solution 2 - Python

A nan is a floating point only thing, there is no representation of it in the integers, so no :)

Pick an invalid value, like -99999

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYarivView Question on Stackoverflow
Solution 1 - PythonPierre GMView Answer on Stackoverflow
Solution 2 - PythonJulianView Answer on Stackoverflow