python - Pandas 用 NaT 替换 NaN

标签 python pandas

我有一个包含一些 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,因为当dtypefloat时,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/

相关文章:

c++ - 说 C++ 中的数组或 Python 中的列表是类是否正确?数据结构?或两者?

python - 从 Groupby 创建新的 Pandas 列并划分其他列

python - 填充具有多个系列的 pandas 数据框的缺失日期

python - Beatbox:从 ​​SFDC 提取数据时如何添加 WHERE 子句?

python - 如何停止和重启 Telegram Bot

python - 为什么 "Models aren' t 已加载”?

python - Pandas group by 将不同的行转换为具有值数组的一行

python - 禁用 sqlalchemy 事件监听器的方法

python - 处理闰年并替换新日期

python - 在 Pandas 数据框替换功能中使用正则表达式匹配组