Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy integer nan [duplicate]

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
like image 990
Yariv Avatar asked Oct 03 '12 12:10

Yariv


People also ask

Is NaN an integer Python?

In Python, NaN stands for Not a Number. This error will occur when we are converting the dataframe column of the float type that contains NaN values to an integer.

Does NumPy support NaN?

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

Can NaN be an integer?

NaN is short for Not a Number . It is a numeric data type used to represent any value that is undefined or unpresentable. The ValueError: cannot convert float NaN to integer raised because of Pandas doesn't have the ability to store NaN values for integers.

How do I replace 0 with NaN NumPy?

nan_to_num() in Python. numpy. nan_to_num() function is used when we want to replace nan(Not A Number) with zero and inf with finite numbers in an array. It returns (positive) infinity with a very large number and negative infinity with a very small (or negative) number.


2 Answers

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)
like image 88
Pierre GM Avatar answered Oct 22 '22 18:10

Pierre GM


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

like image 11
Julian Avatar answered Oct 22 '22 17:10

Julian