pandas datetimeindex的between_time函数(如何获取不在时间范围内)

2 投票
1 回答
637 浏览
提问于 2025-04-17 21:34

我有一个 pandas 数据框,我用 between_time 这个功能来清理数据。请问我怎么才能实现不在这个时间范围内的效果呢?

我知道我可以尝试类似这样的做法。

df.between_time['00:00:00', a]   
df.between_time[b,23:59:59']

然后把结果合并起来并对新的数据框进行排序。不过这样效率很低,而且对我来说不太好用,因为我有一些数据是在 23:59:59 和 00:00:00 之间的。

谢谢!

1 个回答

2

你可以找到时间在 ab 之间的行的索引位置,然后使用 df.index.diff 来从索引中删除这些行:

import pandas as pd
import io
text = '''\
date,time, val
20120105, 080000,   1
20120105, 080030,   2
20120105, 080100,   3
20120105, 080130,   4
20120105, 080200,   5
20120105, 235959.01, 6
'''

df = pd.read_csv(io.BytesIO(text), parse_dates=[[0, 1]], index_col=0)
index = df.index
ivals = index.indexer_between_time('8:01:30','8:02')
print(df.reindex(index.diff(index[ivals])))

这样就得到了

                             val
date_time                       
2012-01-05 08:00:00            1
2012-01-05 08:00:30            2
2012-01-05 08:01:00            3
2012-01-05 23:59:59.010000     6

撰写回答