Why is numpy telling me that I can't convert a float NaN when I'm actually trying to convert an int?

Viewed 360

Here is a simple numpy array:

import numpy as np
x = np.array([15, 22, 3])

I want to transform the second value into nan:

x[1] = np.nan

It returns the following error:

ValueError: cannot convert float NaN to integer

print(type(x[1]))  # this returns "<class 'numpy.int32'>"

I managed to replace the required value with NaN by transforming the array of ints into an array of floats.

But still. Why is numpy telling me that I can't convert a float NaN when I'm actually trying to convert an int?

Thank you

2 Answers

In numpy, nan is a special float:

>>> type(np.nan)
<class 'float'>

I call it a special type of float because normally Python won't complain if you try to add both int and float into a single numpy array since the integers will automatically be converted to float:

>>> x = np.array([-1, float(10.12)])
>>> x
>> array([-1.  , 10.12])

but this is not the case for numpy.nan:

IEEE 754 floating point representation of Not a Number (NaN).


I would suggest to either create a numpy array of floats:

import numpy as np
x = np.array([15.0, 22.0, 3.0])
x[1] = np.nan

>>> array([15., nan,  3.])

or try to represent nan using an alternative integer value if your use-case allows this representation. For instance use -1 to represent nan (for example this would make sense if in your use case you don't have negative values).


Alternatively, you can use a list that allows you to store objects of different data type:

l = [15, 22, 3]
l[1] = np.nan

>>> [15, nan, 3]
Related