【问题标题】:Using np.searchsorted to find the most recent timestamp使用 np.searchsorted 查找最近的时间戳
【发布时间】:2015-06-01 05:30:05
【问题描述】:

我有两个列表,每个列表都填充了时间戳,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 循环。

【问题讨论】:

  • np.searchsortedside关键字参数,我想你只需要设置side='right',80%就可以了。
  • 谢谢!我不太确定这与仅交换参数顺序有何不同。两者是等价的吗?
  • 他们无事可做...我已经给出了完整的答案,看看是否有意义。
  • 啊,是的。它做了一些完全不同的事情。你说的对。并感谢您提供完整的答案。我已经接受了。我刚刚用我的代码对其进行了测试,它可以工作。

标签: python numpy timestamp


【解决方案1】:

为了让我们的生活更轻松,让我们使用数字而不是时间戳:

>>> 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])

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2015-08-19
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多