在 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
请您参考如下方法:
您可以将持续时间添加到 Index 以获得结束时间,但即使是 0 秒,您也需要使用 ffill:
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
