gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:37:17 25 4
gpt4 key购买 nike

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

我有一张图表显示温度主要是深度的非线性函数,其中 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 值,这不是数据集中的原始温度值之一。我尝试了以下步骤:

np.interp(22.61, x1, y1)

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

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 的新手,所以如果我需要重新表述问题,请告诉我。

最佳答案

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

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)


完整代码:

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

enter image description here

关于python - 插值时间序列,从x中选择y值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50583392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com