Pandas DataFrame Replace NaT with None

I struggled with this issue for a long time and tried different methods.

I have a simple DataFrame as shown in the picture,

enter image description here

I can use the code to replace NaNwith None(not String "None"),

[![dfTest2 = dfTest.where(pd.notnull(dfTest), None)][2]][2]

enter image description here

I support that is NaTalso classified as "zero" because the following,enter image description here

However, NaTnot replaced by None.

I was looking for answers, but I had no luck. Can anybody help?

Thanks in advance.

+9
source share
2 answers

Do dtype object

dfTest2 = pd.DataFrame(dict(InvoiceDate=pd.to_datetime(['2017-06-01', pd.NaT])))

dfTest2.InvoiceDate.astype(object).where(dfTest2.InvoiceDate.notnull(), None)

0    2017-06-01 00:00:00
1                   None
Name: InvoiceDate, dtype: object
+13
source

Make the column type first as str

 dfTest2.InvoiceDate =  dfTest2.InvoiceDate.astype(str)

"NaT" None

dfTest2.InvoiceDate = dfTest2.InvoiceDate.apply(lambda x : None if x=="NaT" else x)
0

Source: https://habr.com/ru/post/1672395/


All Articles