Pandas DataFrame Replace NaT with None

前端 未结 4 861
南笙
南笙 2020-12-14 08:55

I have been struggling with this question for a long while, and I tried different methods.

I have a simple DataFrame as shown,

I can use code to rep

相关标签:
4条回答
  • 2020-12-14 09:12

    The simplest solution I found that worked for me is...

    Input:

    import pandas as pd
    import numpy as np
    dfTest = pd.DataFrame(dict(InvoiceDate=pd.to_datetime(['2017-06-01', pd.NaT]), CorpId=[2997373, np.nan], TestName=[1,1]))
    dfTest.replace({np.nan: None})
    

    Output of dfTest:

    0 讨论(0)
  • 2020-12-14 09:25

    Similar approach as suggested by @neerajYadav but without the apply:

    dfTest2['InvoiceDate'] = (dfTest2['InvoiceDate']
                              .astype(str) # <- cast to string to simplify
                                           #    .replace() in newer versions
                              .replace({'NaT': None} # <- replace with None
                             )
    
    0 讨论(0)
  • 2020-12-14 09:30

    Make the 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
    
    0 讨论(0)
  • 2020-12-14 09:34

    Make the column type as str first

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

    then compare it directly with "NaT" and replace with None

    dfTest2.InvoiceDate = dfTest2.InvoiceDate.apply(lambda x : None if x=="NaT" else x)
    
    0 讨论(0)
提交回复
热议问题