草庐IT

python Pandas : drop rows of a timeserie based on time range

coder 2023-08-20 原文

我有以下时间序列:

start = pd.to_datetime('2016-1-1')
end = pd.to_datetime('2016-1-15')
rng = pd.date_range(start, end, freq='2h')
df = pd.DataFrame({'timestamp': rng, 'values': np.random.randint(0,100,len(rng))})  
df = df.set_index(['timestamp'])

我想删除这两个时间戳之间的行:

start_remove = pd.to_datetime('2016-1-4')
end_remove = pd.to_datetime('2016-1-8')

我该怎么做?

最佳答案

使用query

df.query('index < @start_remove or index > @end_remove')

使用 loc

df.loc[(df.index < start_remove) | (df.index > end_remove)]

使用日期切片

这包括终点

pd.concat([df[:start_remove], df[end_remove:]])

没有终点

pd.concat([df[:start_remove], df[end_remove:]]).drop([start_remove, end_remove])

关于 python Pandas : drop rows of a timeserie based on time range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41513324/

有关python Pandas : drop rows of a timeserie based on time range的更多相关文章

随机推荐