Pandas DataFrame将NaT替换为None

eqoofvh9  于 2023-05-15  发布在  其他
关注(0)|答案(8)|浏览(278)

我已经为这个问题挣扎了很长一段时间,我尝试了不同的方法。
我有一个简单的DataFrame,如图所示,

我可以使用代码将NaN替换为None(Not String“None”),
[![dfTest2 = dfTest.where(pd.notnull(dfTest), None)][2]][2]

我支持NaT也被归类为“Null”,因为下面的

但是,NaT不会被None替换。
我一直在寻找答案,但没有运气。任何人都可以帮助?
先谢谢你。

tuwxkamq

tuwxkamq1#

使dtypeobject

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
aemubtdh

aemubtdh2#

我发现对我有效的最简单的解决方案是...

输入:

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}, inplace = True)

dfTest输出:

3npbholx

3npbholx3#

列类型先为str

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

然后直接与“NaT”比较,替换为None

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

esbemjvw4#

与@neerajYadav建议的方法类似,但没有apply

dfTest2['InvoiceDate'] = (dfTest2['InvoiceDate']
                          .astype(str) # <- cast to string to simplify
                                       #    .replace() in newer versions
                          .replace({'NaT': None} # <- replace with None
                         )
qni6mghb

qni6mghb5#

df.fillna(None)仅适用于np.na,而不适用于pd.NaT。但是,执行df.replace({np.nan: None})pd.NaTnp.na替换为None

# Initalize a sample dataframe
df = pd.DataFrame({
                    'start_date': pd.to_datetime(['2017-06-01', pd.NaT]), 
                    'amount':[2997373, np.nan]
                   })
display(df)

# Then replace pd.NaT and np.na with None
df = df.replace({np.nan: None})
display(df)
sxissh06

sxissh066#

这看起来很奇怪,但对我很有效。Pandas版本14.1

import numpy as np

df = df.replace(np.NaN, 0).replace(0, None)

最后修改日期前NaT
LastModifiedDate后

xdnvmnnf

xdnvmnnf7#

我在这里看到了其他几个类似的答案,尽管没有一个像这样简单:

df.replace([pd.NaT], [None])
pkln4tw6

pkln4tw68#

如果你不想改变列的类型,那么另一种方法是先用np.nan替换所有缺失值(pd.NaT),然后用None替换后者:

import numpy as np

df = df.fillna(np.nan).replace([np.nan], [None])

相关问题