Python Pandas:根据时间范围删除时间序列的行

jim*_*iat 8 python pandas

我有以下时间服务:

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'])
Run Code Online (Sandbox Code Playgroud)

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

start_remove = pd.to_datetime('2016-1-4')
end_remove = pd.to_datetime('2016-1-8')
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

piR*_*red 9

运用 query

df.query('index < @start_remove or index > @end_remove')
Run Code Online (Sandbox Code Playgroud)

运用 loc

df.loc[(df.index < start_remove) | (df.index > end_remove)]
Run Code Online (Sandbox Code Playgroud)

使用日期切片

这包括终点

pd.concat([df[:start_remove], df[end_remove:]])
Run Code Online (Sandbox Code Playgroud)

并没有终点

pd.concat([df[:start_remove], df[end_remove:]]).drop([start_remove, end_remove])
Run Code Online (Sandbox Code Playgroud)


Joe*_*fer 6

df = df.drop(pd.date_range('2018-01-01', '2018-02-01')), errors='ignore')
Run Code Online (Sandbox Code Playgroud)