Pandas DataFrame 用 None 替换 NaT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42818262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas DataFrame Replace NaT with None
提问by Haipeng Su
I have been struggling with this question for a long while, and I tried different methods.
我一直在为这个问题苦苦挣扎,我尝试了不同的方法。
I have a simple DataFrame as shown,
我有一个简单的 DataFrame,如图所示,
I can use code to replace NaN
with None
(Not String "None"),
我可以使用代码替换NaN
为None
(Not String "None"),
[![dfTest2 = dfTest.where(pd.notnull(dfTest), None)][2]][2]
[![dfTest2 = dfTest.where(pd.notnull(dfTest), None)][2]][2]
I support that NaT
is also classified as 'Null' because the following,
However, NaT
is not replaced with None
.
但是,NaT
没有替换为None
。
I have been searching for answers but got no luck. Anyone could Help?
我一直在寻找答案,但没有运气。任何人都可以帮助?
Thank you in advance.
先感谢您。
回答by piRSquared
Make the dtype
object
使 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
回答by Neeraj Yadav
Make the column type as str first
首先将列类型设为 str
dfTest2.InvoiceDate = dfTest2.InvoiceDate.astype(str)
then compare it directly with "NaT" and replace with None
然后直接与“NaT”进行比较并替换为None
dfTest2.InvoiceDate = dfTest2.InvoiceDate.apply(lambda x : None if x=="NaT" else x)
回答by dshefman
The simplest solution I found that worked for me is...
我发现对我有用的最简单的解决方案是......
Input:
输入:
dfTest = pd.DataFrame(dict(InvoiceDate=pd.to_datetime(['2017-06-01', pd.NaT])))
dfTest.replace({pd.np.nan: None})
Output:
输出:
Note: pd.np.nan is provided by pandas, so that you don't have to import numpy to use np.nan.
注意:pd.np.nan 是由pandas 提供的,所以你不必导入numpy 来使用np.nan。