a=np.random.randint(15,size=[2,5])
b=np.random.random([2,5])
b[0,2]=np.nan
a[0,2]=np.nan
I can easily replace any indices of b with nan. But if the same command I am trying to repeat for a, it's showing error. Why? How do I resolve that? Why is this happen?
Numpy treat
NaN
as a
float
. You cannot use it in an integer array.
Instead, you can use an invalid value:
a[0, 2] = -99999
Insert this line after assignments - and it will become clear
print(a.dtype, type(np.nan))
Though exception - which you should have posted - explains it rather clearly
Error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-10-363eed6533b3> in <module>()
----> 1 a[0,2] = np.nan
ValueError: cannot convert float NaN to integer
(Jul-02-2018, 11:40 AM)volcano63 Wrote: [ -> ]ValueError: cannot convert float NaN to integer
The ValueError: cannot convert
float NaN to integer raised because of Pandas doesn't have the ability to store NaN values for integers. From Pandas v0.24, introduces Nullable Integer Data Types which allows integers to coexist with NaNs. This does allow integer NaNs . This is the pandas integer, instead of the numpy integer.
df['column_name'].astype(np.float).astype("Int32")