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

R-L*_*art 5 python interpolation matplotlib

我一直在寻找这个问题的答案,并且已经接近但不断遇到错误。有很多类似的问题几乎可以回答这个问题,但我一直无法解决。感谢任何帮助或正确方向的观点。

我有一个图表,将温度显示为深度的非线性函数,其中 x 和 y 值来自熊猫数据框。

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')
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

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

np.interp(22.61, x1, y1)
Run Code Online (Sandbox Code Playgroud)

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

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')
Run Code Online (Sandbox Code Playgroud)

我正在尝试设置一个框架并强制进行插值。我也试过

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]
Run Code Online (Sandbox Code Playgroud)

但这会返回特定的、已经列出的 x 值的 y 值,而不是内插值。

我希望这已经足够清楚了。我是数据科学和 stackoverflow 的新手,所以如果我需要重新表述这个问题,请告诉我。

Imp*_*est 6

您确实可以使用该numpy.interp功能。正如文档所述

数据点的 x 坐标必须递增 [...]

因此,在使用此函数之前,您需要对 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)
Run Code Online (Sandbox Code Playgroud)


完整代码:

import numpy as np
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)

# 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)

#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')
plt.plot(x0,y0, marker="o", color="C3")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述