python - apply.pd.to_date_Time。申请取消映射/处理 NaT

标签 python pandas

我对下面的代码测试数据以及解释所遇到的问题有点困惑。

test = {"Med to Ind Date": ['', '', 1402531200000000000, '', 1402876800000000000], 
        "Med to Ind Indicator": ['', '', 'Y', '', 'Y']}
test = pd.DataFrame(test)
date_fields = ["Med to Ind Date"]
test.loc[:, date_fields] = test.loc[:, date_fields].apply(pd.to_datetime)

因此,当您运行上述代码时,您将看到所有空白时间字段都映射到 NaT。这很好,但是它中断了我的下面的代码:

if "Med to Ind Indicator" in test.columns:
    test["Med to Ind Indicator"] = np.where(test["Med to Ind Date"] != '', "Yes", '')

上面的代码查看“Med to Ind Date”字段,如果该字段不为空,则将“Med to Ind Indicator”列映射为“Yes”。 我所做的工作是尝试将 pd.NaT 替换为“”,这有效,但它反过来又取消了我的 date_time 转换,并将其返回到原始形式。你们能推荐一个替代方案吗?另外,pandas 到底是如何看待 NaT 字段的呢?

最佳答案

使用 isnull()(或 notnull())测试 NaT:

np.where(test["Med to Ind Date"].isnull(), '', "Yes")

测试的结果输出:

       Med to Ind Date Med to Ind Indicator
0                 None                     
1                 None                     
2  1402531200000000000                  Yes
3                 None                     
4  1402876800000000000                  Yes

关于python - apply.pd.to_date_Time。申请取消映射/处理 NaT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45600941/

相关文章:

python - 请指点我关于等 ionic 开发的 QT 布局的(好的)文档

python - 非常基本的闹钟打不开网页浏览器

python - dcos cassandra子命令错误

python - 使用日期时间绘制切片 Pandas 数据框时出现 KeyError

python - 使用 pandas 跨多个列进行选择

python - 从列表中的元素中提取 url

python - 如何有效地连接数据框列表?

python - 用其他时间间隔填补时间间隔中的空白

python - 电子邮件中的奇怪字符无法被 imap 服务器摄取

python - python中的负零