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

时间:2015-03-27 18:59:38

标签: python numpy timestamp

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

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

但有点不同。

令我感到尴尬的是,我不能如何扭转这一点,因此它抓住了< = timestamp而不是> =时间戳,但我已经使用了一段时间而且它看起来不那么明显了。我的示例代码是:

#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循环。

1 个答案:

答案 0 :(得分:2)

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

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

ab中小于或等于[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]) ,那么您将在第二个字词中获得错误的值,其中两个数组中都有完全匹配的时间戳:

{{1}}