我已经为这个问题挣扎了很长一段时间,我尝试了不同的方法。我有一个简单的DataFrame,如图所示,
我可以使用代码将NaN替换为None(Not String“None”),[![dfTest2 = dfTest.where(pd.notnull(dfTest), None)][2]][2]
NaN
None
[![dfTest2 = dfTest.where(pd.notnull(dfTest), None)][2]][2]
我支持NaT也被归类为“Null”,因为下面的
NaT
但是,NaT不会被None替换。我一直在寻找答案,但没有运气。任何人都可以帮助?先谢谢你。
tuwxkamq1#
使dtypeobject
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
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输出:
3npbholx3#
列类型先为str
dfTest2.InvoiceDate = dfTest2.InvoiceDate.astype(str)
然后直接与“NaT”比较,替换为None
dfTest2.InvoiceDate = dfTest2.InvoiceDate.apply(lambda x : None if x=="NaT" else x)
esbemjvw4#
与@neerajYadav建议的方法类似,但没有apply:
apply
dfTest2['InvoiceDate'] = (dfTest2['InvoiceDate'] .astype(str) # <- cast to string to simplify # .replace() in newer versions .replace({'NaT': None} # <- replace with None )
qni6mghb5#
df.fillna(None)仅适用于np.na,而不适用于pd.NaT。但是,执行df.replace({np.nan: None})将pd.NaT和np.na替换为None。
df.fillna(None)
np.na
pd.NaT
df.replace({np.nan: 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)
sxissh066#
这看起来很奇怪,但对我很有效。Pandas版本14.1
import numpy as np df = df.replace(np.NaN, 0).replace(0, None)
最后修改日期前NaTLastModifiedDate后无
xdnvmnnf7#
我在这里看到了其他几个类似的答案,尽管没有一个像这样简单:
df.replace([pd.NaT], [None])
pkln4tw68#
如果你不想改变列的类型,那么另一种方法是先用np.nan替换所有缺失值(pd.NaT),然后用None替换后者:
np.nan
import numpy as np df = df.fillna(np.nan).replace([np.nan], [None])
8条答案
按热度按时间tuwxkamq1#
使
dtype
object
aemubtdh2#
我发现对我有效的最简单的解决方案是...
输入:
dfTest输出:
3npbholx3#
列类型先为str
然后直接与“NaT”比较,替换为None
esbemjvw4#
与@neerajYadav建议的方法类似,但没有
apply
:qni6mghb5#
df.fillna(None)
仅适用于np.na
,而不适用于pd.NaT
。但是,执行df.replace({np.nan: None})
将pd.NaT
和np.na
替换为None
。sxissh066#
这看起来很奇怪,但对我很有效。Pandas版本14.1
最后修改日期前NaT
LastModifiedDate后无
xdnvmnnf7#
我在这里看到了其他几个类似的答案,尽管没有一个像这样简单:
pkln4tw68#
如果你不想改变列的类型,那么另一种方法是先用
np.nan
替换所有缺失值(pd.NaT
),然后用None
替换后者: