插值时间序列,从x中选择y值

2024-06-28 19:38:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在寻找这个问题的答案已经有一段时间了,虽然已经接近了,但还是不断地遇到错误。有很多类似的问题几乎可以回答这个问题,但我一直没能解决。任何帮助或在正确方向上的一点都是感激的。在

我有一个图表,显示温度是深度的非线性函数,x和y值取自pandas数据框。在

import matplotlib.pyplot as plt

x = (22.81,  22.81,  22.78,  22.71,  22.55,  22.54,  22.51,  22.37)
y = (5, 16, 23, 34, 61, 68, 77, 86)

#Plot details
plt.figure(figsize=(10,7)), plt.plot(style='.-')
plt.title("Temperature as a Function of Depth")
plt.xlabel("Temperature"), plt.ylabel("Depth")
plt.gca().invert_yaxis()
plt.plot(x,y, linestyle='--', marker='o', color='b')

这给了我一个有点像这个的图像(注意翻转的y轴,因为我说的是深度):

enter image description here

我想在特定的x值22.61处找到y值,这不是数据集中的原始温度值之一。我尝试了以下步骤:

^{pr2}$

这给了我一个我知道不正确的值

s = pd.Series([5,16,23,34,np.nan,61,68,77,86], index=[22.81,22.81,22.78,22.71,22.61,22.55,22.54,22.51,22.37])
s.interpolate(method='index')

我试图建立一个框架,并强制插值。我也试过了

line = plt.plot(x,y)
xvalues = line[0].get_xdata()
yvalues = line[0].get_ydata()
idx = np.where(xvalues==xvalues[3]) ## 3 is the position
yvalues[idx]

但这将返回一个特定的,已经列出的x值的y值,而不是一个插值的值。在

我希望这足够清楚。我对数据科学和stackoverflow都是全新的,所以如果我需要重新措辞,请让我知道。在


Tags: 数据getindexplotasnplineplt
2条回答

您确实可以使用^{}函数。如文件所述

The x-coordinates of the data points, must be increasing [...]

所以在使用这个函数之前,需要对x数组上的数组进行排序。在

# Sort arrays
xs = np.sort(x)
ys = np.array(y)[np.argsort(x)]

# x coordinate
x0 = 22.61
# interpolated y coordinate
y0 = np.interp(x0, xs, ys)


完整代码: ^{pr2}$

enter image description here

在 我认为Scipy提供了一个更直观的API来解决这个问题。然后,您可以轻松地继续使用Pandas中的数据。在

from scipy.interpolate import interp1d
x = np.array((22.81,  22.81,  22.78,  22.71,  22.55,  22.54,  22.51,  22.37))
y = np.array((5, 16, 23, 34, 61, 68, 77, 86))

# fit the interpolation on the original index and values
f = interp1d(x, y, kind='linear')

# perform interpolation for values across the full desired index
f([22.81,22.81,22.78,22.71,22.61,22.55,22.54,22.51,22.37])

输出:

^{pr2}$

您也可以选择多个其他非线性插值(二次、三次等)。查看综合interpolation documentation了解更多详细信息。在

[Edit]:您需要按照@ImportanceOfBeingErnest添加的内容,在x轴上对数组进行排序。在

相关问题 更多 >