首页 > 解决方案 > np.busday_count 与 NaT

问题描述

我正在使用np.busday_count计算两列日期之间的差异,但有些值是 NaT。

in:

df = pd.DataFrame({
    'start_date':[np.datetime64('2021-06-28 21:30:22'),np.datetime64('2021-07-29 21:12:58'), np.datetime64('2021-07-23 17:57:58')], 
    'end_date': [np.datetime64('2021-06-28 21:34:13'),np.datetime64('2021-08-03 11:34:55'), np.datetime64('NaT')]
    })


A = [d.date() for d in df['start_date']]
B = [d.date() for d in df['end_date']]
df['diff'] = np.busday_count(A, B)

这是预期的结果:

  |         start_date |           end_date | diff
0 |2021-06-28 21:30:22 |2021-07-28 21:34:13 |   22
1 |2021-07-29 21:12:58 |2021-08-03 11:34:55 |    3
2 |2021-07-23 17:57:58 |                NaT |  NaN

但它返回以下错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 5, in busday_count
ValueError: cannot convert float NaN to integer

解决这个问题的最佳方法是什么?

标签: pythonpandasnumpy

解决方案


使用 for 循环更改代码busday_count未矢量化

l = [np.busday_count(x, y) if x ==x and y == y else pd.NaT for x,y in zip(A,B) ]
Out[632]: [0, 3, NaT]

推荐阅读