Python |如何插入两个测量值以使 x 值相同

Python | How interpolate two measurements such that the x-values are the same

我有两个测量值,由 x 和 y 值对组成。我想计算这两个系列之间的差异。问题是我不能简单地计算这两个测量值之间的差异,因为它们在 x 值中的采样方式不同。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

x1 = np.array([1, 2, 3, 4, 5])
y1 = np.array([1, 4, 9, 16, 25])
x2 = np.array([1.5, 2.5, 3.3, 4.2, 5.1])
y2 = np.array([1.3, 2.5, 3.3, 4.2, 5.1])
df = np.array([x1, y1, x2, y2])
df = pd.DataFrame(df.T, columns=['x1', 'y1', 'x2', 'y2'])
df.head()

plt.plot(df.x1.values, df.y1.values, df.x2.values, df.y2.values)

我想分配一个新变量 x = np.linspace(0, 5, 100, endpoint=True) 然后通过内插 y1 确定新的 y1_new 和 y2_new和 x.

值上的 y2 值

我看过 pandas.resample() 但它似乎与时间戳有关。也许 'scipy.interpolate' 可以提供帮助,但我不确定这些功能。原则上,我知道如何在 python 中手动编程,但我确信已经有解决我的问题的方法。

使用 scipy.interpolate 的示例是:

import scipy.interpolate as interp
import numpy as np
x1 = np.array([1, 2, 3, 4, 5])
y1 = np.array([1, 4, 9, 16, 25])
new_x1 = np.linspace(0, 5, 100, endpoint=True)
interpolated_1 = interp.interp1d(x1, y1, fill_value="extrapolate")
new_y1 = interpolated_1(new_x1)
new_y1

所有其他方法或多或少都遵循相同的签名,如您在 docs 中所见。使用哪个取决于您拥有的基础数据,例如,第一个看起来像二次方,第二个看起来像恒等式。