【问题标题】:Filter pandas dataframe by several time periods?按几个时间段过滤熊猫数据框?
【发布时间】:2020-10-20 02:43:39
【问题描述】:

我有一个数据框,其中有一个时间戳列(最初是使用 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 吗?我需要制作一个参考字典来配对不同时间段的开始/结束时间吗?

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

感谢您提供的任何帮助。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    只需使用布尔条件,在时间段之间使用“&”。

    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 之间的日期,日期更小(2019 年 8 月 1 日)(那些日期格式为“dd/mm/yyyy”,而在代码中我的格式是“yyyy -mm-dd”)。它会随着时间的推移而起作用

    【讨论】:

      猜你喜欢
      • 2016-05-05
      • 2019-04-13
      • 2018-08-16
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      相关资源
      最近更新 更多