pandas 大熊猫用 NaT 替换 NaN
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37167314/
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 replace NaN with NaT
提问by LateCoder
I have a series with some NaNs that I need to replace with NaTs. How can I do this?
我有一系列需要用 NaT 替换的 NaN。我怎样才能做到这一点?
Here's a simple example with what I've tried so far:
这是我迄今为止尝试过的一个简单示例:
>>> 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 version: 0.16.2
Pandas版本:0.16.2
numpy version: 1.9.2
numpy 版本:1.9.2
python version: 2.7.10
蟒蛇版本:2.7.10
回答by EdChum
Convert the dtype
first as NaT
is meaningless when the dtype
is float
which is the dtype
initially:
当is是初始时,将第dtype
一个 as转换NaT
为毫无意义:dtype
float
dtype
In [90]:
s.astype(np.datetime64).fillna(pd.NaT)
Out[90]:
0 NaT
1 NaT
dtype: datetime64[ns]
if You have non-NaN
values in the Series then use to_datetime
:
如果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]