gpt4 book ai didi

python - scipy中重采样数组的索引

转载 作者:行者123 更新时间:2023-11-30 23:38:22 25 4
gpt4 key购买 nike

我有两个长度相同的一维数组,例如包含时间序列和值序列

t = linspace(0, 5, 5) # [0, 1.25, 2.5, 3.75, 5]
x = array(range(10, 25)) # [10, 11, 12, 13, 14]

例如,我必须使用不同的采样点及时对 x 数组进行重新采样(具有相同的起点和终点,但可以有任意数量的元素)

r = linspace(0, 5, 4) # [ 0, 1.667, 3.333, 5]
x2 = resample(t, x, r) # [10, 11, 12, 14]

也就是说,r的每个时间点都位于t的两个时间点之间,我想找到两个时间点中较低的点在t中的索引。然后可以从索引数组中获取 x 的相对点。

我想要一个基于向量的解决方案,没有循环,可能使用 scipy 的运算符。如果使用 scipy 的函数会更好。

编辑:这里的代码可以满足我的需要,但是更短、更快且基于向量的解决方案会更好。我找不到(尽管尝试)。

def resample(t, r):
i, j, k = 0, 1, 0
s = []
while j < len(t):
if t[i] <= r[k] < t[j]:
s.append(i)
k += 1
else:
i += 1
j += 1
s.append(len(t) - 1)
return array(s)

最佳答案

以下两个小函数中的第二个可以完成您想要的任务:

def resample_up(t, x, r) :
return x[np.argmax(r[:, None] <= t, axis=1)]

def resample_down(t, x, r) :
return x[::-1][np.argmax(r[:, None] >= t[::-1], axis=1)]

>>> resample_up(t, x, r)
array([10, 12, 13, 14])
>>> resample_down(t, x, r)
array([10, 11, 12, 14])

如果您发现很难弄清楚发生了什么,以下内容可能会有所帮助:

>>> r[:, None] <= t
array([[ True, True, True, True, True],
[False, False, True, True, True],
[False, False, False, True, True],
[False, False, False, False, True]], dtype=bool)
>>> r[:, None] >= t[::-1]
array([[False, False, False, False, True],
[False, False, False, True, True],
[False, False, True, True, True],
[ True, True, True, True, True]], dtype=bool)

然后 np.argmax 返回每行中第一次出现 True 的索引。

编辑 IT 很难让它比一行代码更短,但对于大型数组,性能会受到影响,因为索引查找永远不会在循环的早期中断。因此,对于非常大的数组,使用 python 循环扫描数组可能会更快。对于较小的,它不会:

In [2]: %timeit resample_up(t, x, r)
100000 loops, best of 3: 7.32 us per loop

In [3]: %timeit resample_down(t, x, r)
100000 loops, best of 3: 8.44 us per loop

In [4]: %timeit resample(t, x, r) # modified version of the OP's taking also x
100000 loops, best of 3: 13.7 us per loop

关于python - scipy中重采样数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14615355/

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