首页 > 解决方案 > 根据上行中的值删除时间索引 Pandas 数据框中的 n 行

问题描述

在 Pandas 上工作,需要根据列中的值删除 DataFrame 中的 n 个连续行。

在下面的示例中,在 17:00:01 有一个事件持续 2 秒。在那个时间跨度下降时,我需要以下 2 行。在 17:00:04 有另一个事件,然后应该删除第 17:00:05 行。

不确定如何处理这个问题。在 lamda 中使用遮罩?

t = pd.to_timedelta(df['EventSeconds'], unit='s')
mask = df['2019-01-07 17:00:02' : '2019-01-07 17:00:02' + t]

我有:

Index               EventSeconds OtherColumn
07/01/2019 16:59:59 0            2
07/01/2019 17:00:00 2            3
07/01/2019 17:00:01 0            4
07/01/2019 17:00:02 0            5
07/01/2019 17:00:03 0            6
07/01/2019 17:00:04 1            7
07/01/2019 17:00:05 0            8
07/01/2019 17:00:06 0            9

我需要:

Index               EventSeconds OtherColumn
07/01/2019 16:59:59 0            2
07/01/2019 17:00:00 2            3
07/01/2019 17:00:03 0            6
07/01/2019 17:00:04 1            7
07/01/2019 17:00:06 0            9

标签: pythonpandasdatetimeindex

解决方案


您可以添加持续时间Index以获取结束时间,但您需要使用ffillfor even with 0seconds:

t = pd.to_timedelta(df['EventSeconds'], unit='s')

# print end_times to see details    
end_times = (df['Index'].add(t)                   # calculate the end time
                .where(df['EventSeconds'].ne(0))  # mask the starting events
                .ffill()                          # fill the same end times
            )

df[df['Index'].gt(end_times)| df['EventSeconds'].ne(0) ]

输出:

                Index  EventSeconds
0 2019-07-01 16:59:59             0
1 2019-07-01 17:00:00             2
4 2019-07-01 17:00:03             0
5 2019-07-01 17:00:04             1
7 2019-07-01 17:00:06             0

推荐阅读