- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我在 numpy 中有两个数组,t
和 v
并假设 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
来确保索引介于 0
和 len(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/
现在我正在尝试实现 flash programming specification对于 PIC32MX。我正在使用 PIC32MX512L 和 PIC32MX512H。 PIC32MX512L最终必须
我是一名优秀的程序员,十分优秀!