gpt4 book ai didi

python - 获取与numpy中另一个数组的元素相对应的数组元素

转载 作者:行者123 更新时间:2023-11-28 21:17:04 24 4
gpt4 key购买 nike

假设我在 numpy 中有两个数组,tv 并假设 t 严格单调递增。在我的示例中,t 表示时间点数组,v 表示 body 的相应速度。例如,现在我想要获取 t = 3 时的速度。我该怎么做?

最佳答案

对于仅使用 NumPy 的线性插值,您可以使用 np.interp .例如,

import numpy as np
t = np.linspace(0, 5, 100)
v = np.sin(t)

t=3 时求 v 的线性插值:

In [266]: np.interp(3, t, v)
Out[266]: 0.14107783526460238

请注意,如果您希望在 t 的多个值处插入 v,您可以将可迭代对象作为第一个参数传递给 np.interp:

In [292]: np.interp(np.linspace(t.min(), t.max(), 10), t, v)
Out[292]:
array([ 0. , 0.52741539, 0.8961922 , 0.99540796, 0.79522006,
0.35584199, -0.19056796, -0.67965796, -0.96431712, -0.95892427])

这比一次为一个值重复调用 np.interp 要高效得多。


获取数组的一个元素v,它对应于t=3,您可以使用np.searchsorted :

In [272]: v[np.searchsorted(t, 3)]
Out[272]: 0.11106003812412972

但是请注意,np.searchsorted 返回索引,其中 3 将被插入到 t 中以保持其排序。所以 v[np.searchsorted(t, 3)]v[np.searchsorted(t, 3)+1] 将速度夹在 t=3 处

还要注意 np.searchsorted 可能会返回一个比 t(和 v)的最大有效索引大 1 的索引。如果 3 > t.max() 会发生这种情况:

例如,如果 t[1,2,3]:

In [277]: np.searchsorted([1,2,3], 5)
Out[277]: 3

所以为了防止可能出现的IndexError,使用np.clip来确保索引介于 0len(v)-1 之间:

idx = np.clip(np.searchsorted(t, 3), 0, len(v)-1)
v[idx]

np.interp 一样,np.searchsorted 可以接受一个可迭代对象(这里是第二个参数):

In [306]: v[np.clip(np.searchsorted(t, [3,4,5,6]), 0, len(v)-1)]
Out[306]: array([ 0.11106004, -0.7825875 , -0.95892427, -0.95892427])

关于python - 获取与numpy中另一个数组的元素相对应的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28011142/

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