使用 np.searchsorted 查找最近的时间戳

Using np.searchsorted to find the most recent timestamp

我有两个列表,每个列表都填充了时间戳,list_a 和 list_b。使用 np.searchsorted 为 list_b 中的每个条目查找 list_a 中的最新条目的最佳方法是什么?结果将是 list_a_updated,其中 list_a_updated 中的每个 x 直接匹配到其在 list_b 中对应的(及之后的)条目。这个问题和这个问题非常相似

pandas.merge: match the nearest time stamp >= the series of timestamps

但有点不同。

令我尴尬的是,我无法扭转它,所以它获取 <= 时间戳而不是 >= 时间戳,但我已经使用它一段时间了,它没有看起来那么明显。我的示例代码是:

#in this code tradelist is list_b, balist is list_a

tradelist=np.array(list(filtereddflist[x][filtereddflist[x].columns[1]]))
df_filt=df_filter(filtereddflist2[x], 2, "BEST_BID" )
balist=np.array(list(df_filt[df_filt.columns[1]]))

idx=np.searchsorted(tradelist,balist)-1
mask= idx <=0

df=pd.DataFrame({"tradelist":tradelist[idx][mask],"balist":balist[mask]})

而且解决方案并不只是切换不等式那么简单。

如果有帮助的话,我正在处理交易和出价库存数据,并试图为每笔交易 (list_b) 找到最近的出价 (list_a),而不必求助于一个for循环。

为了让我们的生活更轻松,让我们用数字代替时间戳:

>>> a = np.arange(0, 10, 2)
>>> b = np.arange(1, 8, 3)
>>> a
array([0, 2, 4, 6, 8])
>>> b
array([1, 4, 7])

a 中小于或等于 b 中每个项目的最后时间戳将是 [0, 4, 6],对应于索引 [0, 2, 3],这正是如果我们这样做,我们会得到什么:

>>> np.searchsorted(a, b, side='right') - 1
array([0, 2, 3])
>>> a[np.searchsorted(a, b, side='right') - 1]
array([0, 4, 6])

如果您不使用 side='right' 那么您会得到第二项的错误值,其中两个数组中的时间戳完全匹配:

>>> np.searchsorted(a, b) - 1
array([0, 1, 3])