在 NumPy 中,插值用于估计函数在未知值的点上的值。
假设我们有两个数组:day 表示星期几,gold_price 表示每克黄金的价格。
day = np.array([2, 4, 7])
gold_price = np.array([55, 58, 65])
根据给定的数据集,我们可以说第 2 天黄金的价格是 55。但我们不知道第 3 天黄金的价格。
在这种情况下,我们使用插值来估计数据点之间任何一天的黄金价格。
NumPy 插值
NumPy 提供了一个 interp()
函数来处理插值。我们来看一个例子。
import numpy as np
day = np.array([2, 4, 7])
gold_price = np.array([55, 58, 65])
# find the value of gold on day 3
day3_value = np.interp(3, day, gold_price)
print("The value of gold on day 3 is", day3_value)
输出
The value of gold on day 3 is 56.5
在这里,我们使用了 interp()
函数来查找第 3 天黄金的价格。
我们向 interp()
函数发送了 3 个参数
- 3:需要插值坐标的值
- day:表示星期几的数据点的 x 坐标
- gold_price:表示黄金价格的数据点的 y 坐标
示例:NumPy 插值
import numpy as np
day = np.array([2, 4, 7, 10])
gold_price = np.array([55, 58, 65, 70])
# days whose value is to be interpolated
interpolate_days = np.array([1, 3, 5, 6, 8, 9])
interpolated_price= np.interp(interpolate_days, day, gold_price)
print(interpolated_price)
输出
[55. 56.5 60.33333333 62.66666667 66.66666667 68.33333333]
在此示例中,我们使用了 interp()
函数对数组 interpolate_days 中的值进行插值。
结果数组是第 1、3、5、6、8 和 9 天的估算黄金价格。
绘制插值后的值图
要绘制图表,我们需要从 matplotlib
模块导入 pyplot
。我们来看一个例子。
import numpy as np
import matplotlib.pyplot as plt
# arrays with random data points
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0, 3, 4, 5, 7, 8])
# generate evenly spaced values between the minimum and maximum x values
x_interp = np.linspace(x.min(), x.max(), 100)
# interp() to interpolate y values
y_interp = np.interp(x_interp, x, y)
# plot the original data points and the interpolated values
plt.plot(x, y, 'bo')
plt.plot(x_interp, y_interp, 'r-')
plt.show()
输出

在此示例中,我们绘制了 y_interp 中插值后的值的图。
首先,我们使用 linspace()
函数生成了 x 的最小值和最大值之间的 100 个均匀间隔的值。
然后,我们使用 interp()
函数对 y 值进行插值,并使用 plot()
函数绘制了插值后的值。