问题描述
我必须扩大向量内部的点数,才能将向量扩大到固定大小.例如:
Hi I have to enlarge the number of points inside of vector to enlarge the vector to fixed size. for example:
为此简单向量
>>> a = np.array([0, 1, 2, 3, 4, 5])
>>> len(a)
# 6
现在,我想获得一个大小为11的向量,以a
向量为基础,结果将是
now, I want to get a vector with size of 11 taken the a
vector as base the results will be
# array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ])
编辑1
我需要的是一个函数,该函数将输入基本向量和必须为结果向量的值的数量,然后返回一个新的向量,其大小等于该参数.像
what I need is a function that will enter the base vector and the number of values that must be the resultant vector, and I return a new vector with size equal to the parameter. something like
def enlargeVector(vector, size):
.....
return newVector
使用方式如下:
>>> a = np.array([0, 1, 2, 3, 4, 5])
>>> b = enlargeVector(a, 200):
>>> len(b)
# 200
和b包含线性,三次或任何插值方法的数据结果
and b contains data results of linear, cubic, or whatever interpolation methods
推荐答案
在scipy.interpolate
中有很多方法可以做到这一点.我最喜欢的是UnivariateSpline,它产生一个有序的k
样条,保证可微分的k
次.
There are many methods to do this within scipy.interpolate
. My favourite is UnivariateSpline, which produces an order k
spline guaranteed to be differentiable k
times.
要使用它:
from scipy.interpolate import UnivariateSpline
old_indices = np.arange(0,len(a))
new_length = 11
new_indices = np.linspace(0,len(a)-1,new_length)
spl = UnivariateSpline(old_indices,a,k=3,s=0)
new_array = spl(new_indices)
在这种情况下,s
是一个平滑因子,应将其设置为0(因为数据准确).
The s
is a smoothing factor that you should set to 0 in this case (since the data are exact).
请注意,对于您指定的问题(由于a
只是单调增加1),这是过大的,因为第二个np.linspace
已经提供了所需的输出.
Note that for the problem you have specified (since a
just increases monotonically by 1), this is overkill, since the second np.linspace
gives already the desired output.
阐明了长度是任意的
这篇关于numpy插值以增加向量大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!