如何在pandas中筛选DatetimeIndex落在指定时间区间内的行
pandas 按每日固定时间段筛选的优化方案
报错原因说明
你调用df.index.time时返回的是numpy.ndarray类型,不存在pandas专属的between方法,因此触发报错。
优化实现方案
方案1(推荐):使用DatetimeIndex.indexer_between_time内置方法
这是pandas专门为时间索引设计的时间段筛选接口,无需手动转换时间格式,代码更简洁,性能也优于手动写多条件判断,完全匹配你的筛选逻辑:
import pandas as pd from datetime import datetime # 样例数据 df = pd.DataFrame({ 'date': [datetime(2021, 11, 1, 13, 30), datetime(2021, 11, 2, 13, 31), datetime(2021, 11, 3, 13, 32), datetime(2021, 11, 1, 13, 33)], 'value': [1, 2, 3, 5] }).set_index('date') # 筛选13:30 <= 时间 < 13:32的记录 df = df.iloc[df.index.indexer_between_time('13:30', '13:32', include_end=False)]
参数说明:include_end=False对应你原代码的左闭右开逻辑,如果需要包含结束时间13:32的记录,直接删除该参数即可(默认值为True)。
方案2:兼容between写法
如果需要保留between的写法,可以先将numpy数组转为pandas Series再调用方法:
from datetime import datetime df = df.loc[ pd.Series(df.index.time, index=df.index).between( datetime.strptime("13:30", '%H:%M').time(), datetime.strptime("13:32", '%H:%M').time(), inclusive='left' ) ]
参数说明:inclusive='left'同样用于匹配原代码的左闭右开逻辑。
内容的提问来源于stack exchange,提问作者Andrey
相关产品推荐
相关产品推荐

