【问题标题】:Find the number of rows between two dates based on condition根据条件查找两个日期之间的行数
【发布时间】:2020-05-18 15:50:00
【问题描述】:

我的数据如下所示:

Datetime column     Binary column
2020-01-02 08:30:00 True
2020-01-02 08:31:00 False
2020-01-02 08:32:00 False
2020-01-02 08:33:00 False
2020-01-02 08:34:00 True
.
.
.
2020-01-02 08:58:00 True

如您所见,数据始终以 1 分钟为间隔。此外,还有一个二进制真/假列。

我有一个变量 gap,它指定了两个真之间可能出现的最大连续假数。如果差距更大,我什么都不做;如果间隙较小,我想删除所有受影响的行。在我们的示例中(对于前 5 行),如果 gap=3 或更多,我不想删除任何行。如果间隙较小(1、2),我想删除第 2、3、4 行。

我目前的解决方案通过使用between_dates() 方法解决了这个问题。我用 True 遍历所有日期的压缩列表,并检查其间日期系列的长度是否小于或等于间隙。

您是否知道任何其他方法(最好是矢量化)可以在不使用 for 循环的情况下解决此问题?

【问题讨论】:

  • 您能否添加一个具有预期输出的更好的测试用例?

标签: python pandas


【解决方案1】:

经过几次尝试和错误,我想出了一个办法。我不确定它是否是最佳的,但它是矢量化的。代码如下:

import pandas as pd
import numpy as np

gap = 3  # You can modify this value
# Create dataframe with True/False sequences
tmp = pd.DataFrame([True, False, True, False, False, True, False, False, False, True, False, False,
                    False, False, False, True], columns=['Binary'])
# Convert to zeros and ones to make computations and filtering
tmp['col_0'] = (tmp==False).astype(int)
# Count consecutive False in a vectorized way. Check Note 1 for next line
tmp['col_1'] = ((tmp['col_0'] * (tmp['col_0'].groupby((tmp['col_0'] != tmp['col_0'].shift()).cumsum()).cumcount() + 1)) > gap).astype(int)
# Create NaN in lines we are interested to remove
tmp['col_2'] = tmp['col_1'].replace(1, np.nan)
# Finish creating NaN in lines before we reached the 'gap' value. Check Note 2 for next segment
for counter in range(1, gap + 1):
    tmp['col_2'] = tmp['col_2'] + tmp['col_1'].shift(-counter)
    tmp['col_2'] = tmp['col_2'].replace(1, np.nan)
# The shift() function creates NaN at the end of the Dataframe. I need to verify the last lines (length of dataframe - gap) are ok. Check Note 3
tmp.iloc[np.where(tmp[len(tmp) - gap:]['col_1'] == 0)[0] + len(tmp) - gap, 2] = 0
# Drop the NaN lines
tmp.dropna(inplace=True)

注1:检查python pandas - creating a column which keeps a running count of consecutive values

注 2:我在这里问了一个向量化的问题:How to vectorize a function that uses both row and column elements of a dataframe,@andrej-kesely 非常友好地解决了这个问题。从这里我得到了使用 pd.shift() 的想法。也许这可以以更好的方式进行矢量化,但到目前为止我就是这样理解的

注3:勾选pandas dataframe fails to assign value to slice subset

如您所见,有几个步骤,但都是矢量化的。

如果这有用,我会感谢您的支持并将其标记为解决方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    相关资源
    最近更新 更多