python - dt.time.between 在 pandas 中返回一个空列
问题描述
slots = pd.DataFrame({'times': ['2020-02-01 18:40:00', '2020-02-01 08:40:00',
'2020-02-01 03:40:00', '2020-02-01 14:40:00',
'2010-05-05 22:00:00', '2018-03-08 23:00:00']})
print(slots)
slots['times'] = pd.to_datetime(slots.times)
from datetime import datetime
start = datetime.strptime('17:09:00', '%H:%M:%S').time()
print(start)
end = datetime.strptime('01:59:00', '%H:%M:%S').time()
print(end)
print(slots[slots['times'].dt.time.between(start, end)])
output: Empty DataFrame
Columns: [times]
Index: []
我得到空的数据框。有人可以指导还是有其他方法可以做到这一点。
解决方案
Pandas 有方法DataFrame.between_time
,所以我建议使用它,也添加了它,DataFrame.set_index
因为DataFrame.reset_index
方法适用于DatetimeIndex
:
df = (slots.set_index('times', drop=False)
.between_time('17:09:00', '01:59:00')
.reset_index(drop=True))
print (df)
times
0 2020-02-01 18:40:00
1 2010-05-05 22:00:00
2 2018-03-08 23:00:00
推荐阅读
- ruby-on-rails - Rails:形成多选
- excel - 从打开的工作簿的指定工作表复制数据并将其粘贴到另一个指定的关闭工作簿工作表
- oracle - 使用 IP 地址访问 Oracle 数据库:网络适配器无法建立连接
- javascript - 在渲染之前添加数据后如何获取子组件?
- mongodb - Vue.js 可以根据当前 Date 生成实时事件吗?
- php - Annoation Route 在 symfony 4.2.8 中不起作用
- sql - Oracle SQL 在 IN 子句中传递单引号
- .htaccess - htaccess 多个条件相同的 URL 重定向
- javascript - Javascript如何拆分或破坏6位数字
- azure-ad-b2c - Zebra Enterprise 浏览器 1.7 中的 AD B2C 登录支持