python - 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
解决这个问题的最佳方法是什么?
解决方案
使用 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]
推荐阅读
- javascript - 如何使切换隐藏页面上的所有组件,以便在 react-native 中只有背景图像可见?我
- opengl - 我有一个只有 1 盏灯的公式,但我需要 2 盏灯
- google-apps-script - 找不到在 Google Workspace Marketplace 之前编写的 Google Apps 脚本
- python - Pyinstaller 应用程序关闭并在 30 秒后再次打开
- rust - 在另一个特征上添加一个特征的迭代器
- flutter - MissingPluginException(在通道 com.ryanheise.just_audio.methods 上找不到方法 init 的实现)
- sql - SQL 选定的非聚合值必须是关联组的一部分
- google-cloud-platform - 使用 Container-Optimized OS 为 GCE 实例设置网络 (TCP) 负载均衡器
- oracle-apex - Oracle APEX 20.2 - 在新 TAB 中处理打开应用程序
- shell - 在 Mac 终端上的 sh -c 调用中转义单引号