Pandas DataFrame将NaT替换为None

时间:2017-03-15 18:47:42

标签: python-2.7 pandas dataframe

我一直在努力解决这个问题,我尝试了不同的方法。

我有一个简单的DataFrame,如图所示,

enter image description here

我可以使用代码将NaN替换为None(非字符串"无"),

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

enter image description here

我支持NaT也被归类为' Null'因为以下,  enter image description here

但是,NaT并未替换为None

我一直在寻找答案但没有运气。有人可以帮忙吗?

提前谢谢。

4 个答案:

答案 0 :(得分:13)

制作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

答案 1 :(得分:8)

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

输入:

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})

dfTest的输出:

enter image description here

答案 2 :(得分:0)

首先将列类型设为str

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

然后将其直接与“ NaT”进行比较,并替换为“无”

dfTest2.InvoiceDate = dfTest2.InvoiceDate.apply(lambda x:如果x ==“ NaT” else x,则为空)

答案 3 :(得分:0)

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

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