按最小时间增量对 Pandas 时间序列/数据帧进行重采样/切片

Resample/Slice Pandas Timeseries/Dataframe by minimum timedelta

提问人:Simon 提问时间:6/19/2023 更新时间:6/20/2023 访问量:36

问:

我有一个熊猫数据帧或序列,其时间戳不定期。我想过滤表格,以便在 2 行之间保持最小距离,例如 20 毫秒。距离也可能更大。这是左侧和右侧的示例表,应如何根据最小距离过滤此表。

317   2022-12-31 00:00:00.360               317   2022-12-31 00:00:00.360 
318   2022-12-31 00:00:00.364               318   
319   2022-12-31 00:00:00.368               319
320   2022-12-31 00:00:00.372               320   2022-12-31 00:00:00.372
321   2022-12-31 00:00:00.376               321
322   2022-12-31 00:00:00.380               322
323   2022-12-31 00:00:00.384               323
324   2022-12-31 00:00:00.388               324
325   2022-12-31 00:00:00.392               325   2022-12-31 00:00:00.392
326   2022-12-31 00:00:00.396      ->       326
327   2022-12-31 00:00:00.414               327   2022-12-31 00:00:00.414
328   2022-12-31 00:00:00.416               328
329   2022-12-31 00:00:00.420               329
330   2022-12-31 00:00:00.425               330
331   2022-12-31 00:00:00.428               331
332   2022-12-31 00:00:00.432               332
333   2022-12-31 00:00:00.438               333   2022-12-31 00:00:00.438

这是我到目前为止解决问题的代码。实际上只是一个简单的for循环:

res=[timestamps[0]]
# iterate over all timestamps with correct samplerate in following window
for dtin timestamps[1:]:
    # check if the difference between the current timestamp and the last timestamp in res is equal or bigger than the needed minimum of 20ms =min_delta.
    if dt- res[-1] >= min_delta:
         # if yes, add timestamp to res
         res.append(date)

但是,我的问题是数据帧非常非常大,而简单的for循环效率太低。

我需要一个更快的解决方案,并且已经尝试了 .resample .diff、矢量化和类似的东西,但从未得到想要的结果! 有谁知道我如何有效地解决问题? 感谢您的想法!

Pandas DataFrame 矢量化 切片 重采样

评论


答:

0赞 Quantum 6/20/2023 #1

您可以使用该方法计算每行之间的时间差,然后使用布尔索引根据最小时间差阈值筛选数据帧。下面是一个示例代码片段:diff

import pandas as pd

# create example dataframe with irregular timestamps
df = pd.DataFrame({'timestamp': pd.date_range('2022-12-31 00:00:00', periods=100, freq='5ms')})

# calculate time differences
time_diffs = df['timestamp'].diff()

# set minimum time difference threshold
min_delta = pd.Timedelta('20ms')

# filter dataframe based on time differences
filtered_df = df.loc[time_diffs >= min_delta]

在此代码片段中,计算列中每行之间的时间差。然后我们使用 设置最小增量值 20ms。最后,我们使用布尔索引根据大于或等于最小增量值的时间差来过滤数据帧。df['timestamp'].diff()timestampmin_delta = pd.Timedelta('20ms')df.loc[time_diffs >= min_delta]

这应该为您提供一个筛选的数据帧,其中相邻行之间的时间差大于或等于指定的最小增量值。