Python Forum
cannot replace with np.nan
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
cannot replace with np.nan
#1
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?
Reply
#2
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
Reply
#3
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
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#4
(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")
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020