python - 数组中每个值相对于其他值的最小距离

标签 python numpy data-science

我有两个整数数组 A 和 B。数组 A 和 B 中的值对应于事件 A 和 B 发生的时间点。我想转换 A 以包含自最近事件 b 发生以来的时间。

我知道我需要用 A 的每个元素减去 B 的最接近的较小元素,但我不确定如何做。任何帮助将不胜感激。

>>> import numpy as np

>>> A = np.array([11, 12, 13, 17, 20, 22, 33, 34])
>>> B = np.array([5, 10, 15, 20, 25, 30])

期望的结果:

cond_a = relative_timestamp(to_transform=A, reference=B)
cond_a
>>> array([1, 2, 3, 2, 0, 2, 3, 4])

最佳答案

您可以使用 np.searchsorted找到 A 的元素应该插入到 B 中的索引以保持顺序。换句话说,您正在为 A 中的每个元素找到 B 中最接近的元素:

idx = np.searchsorted(B, A, side='right')
result = A-B[idx-1] # substract one for proper index

根据docs searchsorted 使用 binary search ,因此它可以很好地适应大输入。

关于python - 数组中每个值相对于其他值的最小距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56024634/

相关文章:

python - 如何使用 numpy.char.join?

python - numpy 使用前一行的乘积值作为输入将行与数组的后续行相乘

amazon-web-services - 如何调用 AWS SageMaker 终端节点来获取推理?

python - 滚动到 python selenium 中的特定元素

python - 如何在 PyCharm IDE 中使用子进程模块调用基于 ncurses 的应用程序?

python - Azure Bing 图像搜索客户端抛出找不到资源的错误

r - xgboost 错误 - 当我的标签已经是数字并且我需要结果不在 0 ,1 范围内的数字时,标签必须在 [0,1] 中

python - 如何为使用日期时间的导入函数设置时间?

python - 获取仅包含某些索引的 numpy 数组

python - Pandas中groupby方法的 'level'参数是如何工作的?