Python 如何使用scipy.interpolate.splrep插值曲线?

Python 如何使用scipy.interpolate.splrep插值曲线?,python,scipy,interpolation,Python,Scipy,Interpolation,使用一些实验数据,我一辈子都无法解决如何使用splrep创建B样条曲线。数据如下: 以下是摘录: #Depth Temperature 1 14.7036 -0.02 14.6842 -1.01 14.7317 -2.01 14.3844 -3 14.847 -4.05 14.9585 -5.03 15.9707 -5.99 16.0166 -7.05 16.0147 这是它的一个曲线图,深度在y上,温度在x上: 这是我的密码: import numpy

使用一些实验数据,我一辈子都无法解决如何使用splrep创建B样条曲线。数据如下:

以下是摘录:

#Depth  Temperature
1   14.7036
-0.02   14.6842
-1.01   14.7317
-2.01   14.3844
-3  14.847
-4.05   14.9585
-5.03   15.9707
-5.99   16.0166
-7.05   16.0147
这是它的一个曲线图,深度在y上,温度在x上:

这是我的密码:

import numpy as np
from scipy.interpolate import splrep, splev

tdata = np.genfromtxt('t-data.txt', 
                      skip_header=1, delimiter='\t')
depth = tdata[:, 0]
temp = tdata[:, 1]

# Find the B-spline representation of 1-D curve:
tck = splrep(depth, temp)
### fails here with "Error on input data" returned. ###

我知道我在做一件极其愚蠢的事情,但我就是看不出来。

你只需要把你的价值从最小到最大:)。如果深度是一个列表而不是一个numpy数组,
depth[index]
将抛出一个
TypeError
,这对你来说应该不是一个问题

>>> indices = np.argsort(depth)
>>> depth = depth[indices]
>>> temp = temp[indices]
>>> splrep(depth, temp)
(array([-7.05, -7.05, -7.05, -7.05, -5.03, -4.05, -3.  , -2.01, -1.01,
        1.  ,  1.  ,  1.  ,  1.  ]), array([ 16.0147    ,  15.54473241,  16.90606794,  14.55343229,
        15.12525673,  14.0717599 ,  15.19657895,  14.40437622,
        14.7036    ,   0.        ,   0.        ,   0.        ,   0.        ]), 3)

建议@FerdinandBeyer使用
argsort
而不是我丑陋的“压缩值、排序压缩、重新分配值”方法。

您可能应该使用
np.argsort()
函数对数据进行排序:
index=np.argsort(depth);深度=深度[指数];温度=温度[指数]
。这就省去了元组列表的麻烦。@FerdinandBeyer这是一个比我更好的解决方案!现在编辑它。我在尝试执行
depth[index]
时出错,但请告诉我是否有比
[depth[I]更好的方法用于索引中的I]
。不管怎样,这都是一个更干净的解决方案,谢谢。
depth[index]
相当于
np.array([depth[i]表示索引中的i])
,但要快得多!如果出现错误(什么错误?!),请确保
depth
是一个NumPy数组,而不是列表!我在OP发布的数据上使用了这种方法,效果很好。@adiffertben:这是高级切片语法:
array[start:stop:step]
a[:-1]
表示:整个数组(隐式启动和停止)与步骤-1,即反向
x,y=tdata.T
是为这两列创建视图的方便方法。