我对下面的代码测试数据以及解释所遇到的问题有点困惑。
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/