繁体   English   中英

熊猫根据多个日期时间列选择行

[英]pandas select rows based on multiple datetime columns

我有两列StartTimeEndTime ,我需要选择发生在 7-9 和 18-20 之间的事件。 到目前为止我尝试过的是:

+------------+--------------------------------+-------------------------------+
|            |                StartTime       |            EndTime            |
+------------+--------------------------------+-------------------------------+
|        25  | 2018-05-17 11:52:21.769491600  | 2018-05-17 23:08:35.731376400 |
|        32  | 2018-05-19 14:22:24.141359000  | 2018-05-19 18:37:04.003643800 |
|        42  | 2018-05-22 08:25:01.015975500  | 2018-05-22 22:32:34.249869500 |
|        43  | 2018-05-22 08:46:06.187427200  | 2018-05-22 21:29:17.397438000 |
|        44  | 2018-05-22 13:38:37.289871700  | 2018-05-22 18:38:36.498623500 |
+------------+--------------------------------+-------------------------------+

我从使用它们的数据中提取小时数来计算以下

df = df[((df['start_hr']<=7) & (df['end_hr']>=9)) | ((df['start_hr']<=18) & (df['end_hr']>=20))]

有没有更准确、更快速的替代方法?

它会在一段时间内增加你的内存消耗,但你可以做这样的事情,你创建两个临时列并在它们上使用“df.query”。 确保稍后删除列。

df = df.assign(start_hr=df.start_hr.dt.hour, end_hr=df.end_hr.dt.hour)

df.query('(start_hr <= 7  and end_hr >=9) or (start_hr <= 18  and end_hr >=20) ')

你可以使用这个:


df['start_hr'] = pd.to_datetime(df['start_hr']) 
df['end_hr'] = pd.to_datetime(df['end_hr'])

df['start_hr_day'] = df['start_hr'].dt.day
df['end_hr_day'] = df['start_hr'].dt.day 

df.loc[((df['start_hr_day']<=7) & (df['end_hr_day']>=9))|((df['start_hr_day']<=18) & (df['end_hr_day']>=20))]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM