【问题标题】:Python | How interpolate two measurements such that the x-values are the same蟒蛇 |如何插入两个测量值以使 x 值相同
【发布时间】:2019-04-15 20:19:03
【问题描述】:

我有两个由 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),然后通过在 x 的值上插值 y1 和 y2 值来确定新的 y1_new 和 y2_new。

我看过 pandas.resample() 但这似乎与时间戳一起工作。也许 'scipy.interpolate' 会有所帮助,但我不确定这些功能。原则上,我知道如何在 python 中手动编程,但我确信我的问题已经有了解决方案。

【问题讨论】:

    标签: python interpolation


    【解决方案1】:

    使用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 中所见。使用哪一个取决于您拥有的基础数据,例如,第一个看起来像二次方,第二个看起来像恒等式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 2018-01-16
      • 2019-04-14
      • 1970-01-01
      相关资源
      最近更新 更多