pandas - 获取 datetime 和恒定时间变量 pandas 之间的时间差
问题描述
我有一个 DateTime 列“已结束”,如果时间大于 19:00:00 否则要创建一个新列 0。新列应包含“已结束”和 19:00:00 之间的差异(以小时为单位)。 .
Ended New_Ended
2020-10-31 21:06:30 2.1
2020-10-31 20:29:18 1.5
2020-10-01 19:24:42 0.4
2020-10-03 16:24:42 0.0
datetime64[ns]
同样,如果“开始”在 08:30 之前,则以小时为单位获得“开始”和 8:30 之间的时间差
Open New_Open
2020-10-22 7:56:00 0.56
解决方案
我们试试看
# add 19:00:00 to the starts of the days
end_thresh = df['Ended'].dt.floor('D') + pd.Timedelta('19H')
df['New Ended'] = (df['Ended'].sub(end_thresh) # subtract the threshold
.div(pd.Timedelta('1H')) # divide by 1H
.clip(lower=0) # replace negatives with 0
)
输出:
Ended New_Ended
0 2020-10-31 21:06:30 2.108333
1 2020-10-31 20:29:18 1.488333
2 2020-10-01 19:24:42 0.411667
3 2020-10-03 16:24:42 0.000000
相同的逻辑Open
除了你将交换 thresh 和减法列。
推荐阅读
- android - 您需要使用 OKHTTP3 以 JSON 格式发布请求 - Android
- javascript - 使用 javascript 在 div 中查找链接并转到它
- reactjs - 基于 .env 配置变量渲染基础组件
- django - 无法使用 Django 启动主管
- azure - 间歇性天蓝色 403.14
- python - 将 Groupedby 对象转换为 DataFrame 或系列,无需操作
- python - 在虚拟环境中收到提及 miniconda 的错误消息
- node.js - Google Actions SDK 对话中的第二个请求失败并显示“TypeError:标准不是函数”
- java - 如何在流中使用两个过滤器进行不同的转换
- javascript - 带有 html5 导出按钮的流星表格导出数据