python – 根据其内容将numpy数组拆分为类似的数组

我有一个2D numpy数组,表示曲线的坐标(x,y),我想将该曲线分成相同长度的部分,获得分割点的坐标.

最简单的例子是为两个点定义的一条线,例如[[0,0],[1,1]],如果我想将它分成两部分,结果将是[0.5,0.5],并且三部分[[0.33,0.33],[0.67,0.67]]等.

如何在数据不太简单的大型数组中执行此操作?我试图按照它的长度拆分数组,但结果并不好.

解决方法:

如果我理解得很好,你想要的是一个简单的插值.为此,您可以使用scipy.interpolate(http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html):

from scipy.interpolate import interp1d
f = interp1d(x, y) ## for linear interpolation
f2 = interp1d(x, y, kind='cubic') ## for cubic interpolation
xnew = np.linspace(x.min(), x.max(), num=41, endpoint=False)
ynew = f(xnew) ## or f2(xnew) for cubic interpolation

您可以创建一个函数,该函数返回分割点的坐标,给定x,y和所需点的数量:

def split_curve(x, y, npts):
    from scipy.interpolate import interp1d
    f = interp1d(x, y)
    xnew = np.linspace(x.min(), x.max(), num=npts, endpoint=False)
    ynew = f(xnew)
    return zip(xnew[1:], ynew[1:])

例如,

split_curve(np.array([0, 1]), np.array([0, 1]), 2) ## returns [(0.5, 0.5)]
split_curve(np.array([0, 1]), np.array([0, 1]), 3) ## [(0.33333333333333331, 0.33333333333333331), (0.66666666666666663, 0.66666666666666663)]

请注意,x和y是numpy数组而不是列表.

上一篇:c – B样条曲线


下一篇:LA5009 Error Curves