【问题标题】:pandas: Remove all rows within time interval of another series's time index (i.e. time range exclusion)pandas:删除另一个系列时间索引的时间间隔内的所有行(即时间范围排除)
【发布时间】:2017-02-20 14:49:58
【问题描述】:

假设我有两个数据框:

#df1
time
2016-09-12 13:00:00.017    1.0
2016-09-12 13:00:03.233    1.0
2016-09-12 13:00:10.256    1.0
2016-09-12 13:00:19.605    1.0

#df2
time
2016-09-12 13:00:00.017    1.0
2016-09-12 13:00:00.233    0.0
2016-09-12 13:00:01.016    1.0
2016-09-12 13:00:01.505    0.0
2016-09-12 13:00:06.017    1.0
2016-09-12 13:00:07.233    0.0
2016-09-12 13:00:08.256    1.0
2016-09-12 13:00:19.705    0.0

我想删除 df2 中的所有行,这些行最多为 df1 中时间索引的 +1 秒,因此产生:

#result
time
2016-09-12 13:00:01.505    0.0
2016-09-12 13:00:06.017    1.0
2016-09-12 13:00:07.233    0.0
2016-09-12 13:00:08.256    1.0

最有效的方法是什么?我在 API 中看不到任何对时间范围排除有用的东西。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用pd.merge_asof,这是一个以0.19.0 开头的新包含,并且还接受一个容差参数来匹配指定的时间间隔+/-

    # Assuming time to be set as the index axis for both df's
    df1.reset_index(inplace=True)
    df2.reset_index(inplace=True)
    
    df2.loc[pd.merge_asof(df2, df1, on='time', tolerance=pd.Timedelta('1s')).isnull().any(1)]
    

    请注意,默认匹配是在向后方向进行的,这意味着选择发生在右侧DataFrame(df1)的最后一行,其"on"键(即@987654330 @) 小于或等于左边的 (df2) 键。因此,tolerance 参数仅在此方向(向后)延伸,从而导致- 匹配范围。

    为了使 forwardbackward 查找成为可能,从 0.20.0 开始,这可以通过使用 direction='nearest' 参数并将其包含在函数调用。因此,tolerance 也得到了双向扩展,从而产生了+/- 的带宽匹配范围。

    【讨论】:

    • 哈哈..记得几天前@MaxU 对它的容差参数的评论。
    【解决方案2】:

    与@Nickil Maveli 类似的想法,但使用reindex 构建布尔索引器:

    df2 = df2[df1.reindex(df2.index, method='nearest', tolerance=pd.Timedelta('1s')).isnull()]
    

    结果输出:

    time
    2016-09-12 13:00:01.505    0.0
    2016-09-12 13:00:06.017    1.0
    2016-09-12 13:00:07.233    0.0
    2016-09-12 13:00:08.256    1.0
    

    【讨论】:

      【解决方案3】:

      一种方法是通过时间索引查找(假设两个时间列都是索引):

      td = pd.to_timedelta(1, unit='s')
      df2.apply(lambda row: df1[row.name - td:row.name].size > 0, axis=1)
      

      【讨论】:

        猜你喜欢
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-04
        • 2017-10-19
        • 1970-01-01
        • 2021-04-06
        • 2021-08-21
        相关资源
        最近更新 更多