如何正确筛选DataFrame中每日5:00-11:59的时间段数据?
筛选每日上午5:00-11:59时间段数据的正确方法
问题背景
现有如下DataFrame:
Index Dates 0 2017-01-01 23:30:00 1 2017-01-12 22:30:00 2 2017-01-20 13:35:00 3 2017-01-21 14:25:00 4 2017-01-28 22:30:00 5 2017-08-01 13:00:00 6 2017-09-26 09:39:00 7 2017-10-08 06:40:00 8 2017-10-04 07:30:00 9 2017-12-13 07:40:00 10 2017-12-31 14:55:00
尝试用以下代码筛选所有日期中上午5:00:00到11:59:00的数据:
df_new=df['Dates'].between(('2017-01-01 5:00:00'),('2017-12-31 11:59:00'))
但结果仅最后一条为False,其余均为True——这是因为between是判断日期时间是否在整个时间区间(从2017-01-01 5点到2017-12-31 11:59)内,而非每日的时间段。
正确解决方案
要实现每日的时间段筛选,需提取时间部分(忽略日期)进行判断,以下是三种实用方法:
方法1:直接比较时间对象
先确保Dates列为datetime类型,再提取时间部分进行范围判断:
import pandas as pd # 转换为datetime类型(如果还不是的话) df['Dates'] = pd.to_datetime(df['Dates']) # 定义目标时间段的时间对象 start_time = pd.to_datetime('05:00:00').time() end_time = pd.to_datetime('11:59:00').time() # 生成筛选掩码 mask = (df['Dates'].dt.time >= start_time) & (df['Dates'].dt.time <= end_time) # 获取筛选后的结果 df_new = df[mask]
方法2:通过小时和分钟组合判断
拆分小时和分钟字段,逻辑判断更直观:
df['Dates'] = pd.to_datetime(df['Dates']) # 筛选条件:小时≥5,且(小时<11 或者 小时=11且分钟≤59) mask = (df['Dates'].dt.hour >= 5) & \ ((df['Dates'].dt.hour < 11) | ((df['Dates'].dt.hour == 11) & (df['Dates'].dt.minute <= 59))) df_new = df[mask]
方法3:转换为当日秒数比较
将时间转换为当日的总秒数,用数值范围判断:
df['Dates'] = pd.to_datetime(df['Dates']) # 计算每个时间点在当日的总秒数 day_seconds = df['Dates'].dt.hour * 3600 + df['Dates'].dt.minute * 60 + df['Dates'].dt.second # 5:00的秒数是18000,11:59:00的秒数是43140 mask = (day_seconds >= 18000) & (day_seconds <= 43140) df_new = df[mask]
预期结果
以上方法都会筛选出符合条件的行:
Index Dates 6 2017-09-26 09:39:00 7 2017-10-08 06:40:00 8 2017-10-04 07:30:00 9 2017-12-13 07:40:00
内容的提问来源于stack exchange,提问作者Strovic
相关产品推荐
相关产品推荐

