Python 将.pd.应用于日期时间。应用未映射/处理NaT
我对下面的代码测试数据和解释有点困惑Python 将.pd.应用于日期时间。应用未映射/处理NaT,python,pandas,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
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)
<> P>因此,当您运行上面的代码时,您将看到所有的空时间字段都映射到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指示符列映射为Yes。
我所做的工作是试图用“”替换pd.NaT,但它反过来破坏了我的日期时间转换,并将其恢复为原始形式。你们能推荐一个替代方案吗?另外,熊猫如何准确查看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
太棒了,谢谢你。这也回答了我的第二个问题。因此,Pandas将空时间值视为NaT。
test[date\u fields]=test.loc[:,date\u fields]。apply(pd.to\u datetime,unit='ns',errors='concurve')
-这应该可以回答您的第一个问题。。。