gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:34 25 4
gpt4 key购买 nike

我有两个整数数组 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com