为大型数据帧找到最近日期时间的有效方法

Efficient method to find nearest datetime's for large dataframes

我有一个包含两列的 pandas 数据框,都是日期时间实例。第一列由测量时间组成,第二列是第一列具有恒定偏移的总和。例如,假设恒定偏移量 1 给出:

index Measurement_time offset_time
0 0.1 1.2
1 0.5 1.5
2 1.2 2.2
3 2.4 3.4

我想找到与 offset_time 最匹配的每个 measurement_time 的索引,条件是 measurement_time 必须小于或等于 offset_time.因此,给定示例的解决方案是:

索引 = [2, 2, 2, 3]

我已经尝试使用 get_loc 并制作了一个遮罩,但由于我的数据框很大,这些解决方案效率太低。

如有任何帮助,我们将不胜感激!

让我们使用 np.searchsorted 来查找最接近匹配项的索引

s = df['Measurement_time'].sort_values()
np.searchsorted(s, df['offset_time'], side='right') - 1

结果:

array([2, 2, 2, 3], dtype=int64)

注意:如果您的数据框已经在 Measurement_time

列上排序,您可以跳过 .sort_values 部分