按几个时间段过滤熊猫数据框?

时间:2020-10-19 18:32:08

标签: python pandas

我有一个数据框,其中有一个时间戳列(最初是使用pd.to_datetime转换的字符串值),对其进行了排序并设置为索引。我希望通过此索引过滤数据框,以删除给定时间段内未包括的所有行。

时间段示例为(如果重要,格式为%m /%d /%Y%H:%M:%S.%f):

10/05/2020 13:14:40.980 to 10/05/2020 21:50:52.323  
10/06/2020 06:45:31.839 to 10/06/2020 17:05:11.382  
10/06/2020 22:10:05.872 to 10/07/2020 07:03:52.872  
etc....

我发现df.between_time(*pd.to_datetime(['10/05/2020 13:14:40.980', '10/06/2020 21:50:52.323']).time)可用于选择一个时间段,但是如何一次选择多个时间段呢?可以使用between_time这样吗?我需要制作参考字典来配对不同时间段的开始/结束时间吗?

此外,在执行此过滤步骤时计算从总数中排除的行数也将很有帮助。

感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

只使用布尔条件,时间段之间带有'&'。

import pandas as pd

df = pd.Series(data=1, index=pd.date_range("2019-1-1", "2019-5-1"))
df.loc[(df.index < pd.to_datetime("2019-1-8")) | ((df.index > pd.to_datetime("2019-4-22")) & (df.index < pd.to_datetime("2019-4-25")))]

结果:

2019-01-01    1
2019-01-02    1
2019-01-03    1
2019-01-04    1
2019-01-05    1
2019-01-06    1
2019-01-07    1
2019-04-23    1
2019-04-24    1
dtype: int64

在这里,我过滤了22/4/2019到25/4/2019之间的日期,并使用较小的日期(8/1/2019)(这些日期格式为“ dd / mm / yyyy”,而在代码中,我的格式为“ yyyy -mm-dd”)。时间会一样