我有一个包含一些 NaN 的系列,我需要用 NaT 替换它们。我该怎么做?
这是一个简单的示例,其中包含我到目前为止所尝试的内容:
>>> s = pd.Series([np.NaN, np.NaN])
>>> s.fillna(pd.NaT)
0 NaN
1 NaN
dtype: float64
>>> s.replace(np.NaN, pd.NaT)
0 NaN
1 NaN
dtype: float64
>>> s.where(pd.notnull(s), pd.NaT)
0 NaN
1 NaN
dtype: object
Pandas 版本:0.16.2
numpy 版本:1.9.2
python 版本:2.7.10
最佳答案
首先转换dtype
,因为当dtype
是float
时,NaT
是没有意义的,也就是 dtype
最初:
In [90]:
s.astype(np.datetime64).fillna(pd.NaT)
Out[90]:
0 NaT
1 NaT
dtype: datetime64[ns]
如果系列中有非NaN
值,则使用to_datetime
:
In [97]:
s = pd.Series([np.NaN, np.NaN, 1.0])
pd.to_datetime(s)
Out[97]:
0 NaT
1 NaT
2 1970-01-01 00:00:00.000000001
dtype: datetime64[ns]
关于python - Pandas 用 NaT 替换 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37167314/