You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用scipy.interpolate遇阻:如何让x1,y1匹配x2,y2的数据集尺寸

解决不同长度数据集的尺寸匹配问题

我明白你想把长度为8的(x1,y1)数据集扩展成11个点,来匹配(x2,y2)的尺寸,之前尝试SciPy插值没得到预期结果,大概率是忽略了一个关键细节——插值函数要求输入的x轴数据是单调有序的,你的x1最后几个值是20、15、14,是递减的,这会导致插值逻辑出错。下面给你两种靠谱的解决方法,附上完整代码:

方法1:基于x2的x值进行插值(推荐)

这种方法直接用x2的11个x值作为目标点,插值生成对应的y值,完美匹配x2、y2的尺寸。步骤如下:

  1. 先对x1和y1按x值升序排序,满足插值函数的单调要求
  2. 选择插值方法(线性、三次样条等)创建插值函数
  3. 用x2的x值代入插值函数,得到11个点的y1_new
import numpy as np
from scipy.interpolate import interp1d

# 原始数据
x1 = [0,2,5,10,12,20,15,14]
y1 = [0,0.3,0.6,1.1,1.3,2.1,1.6,1.5]
x2 = [0,2,4,5,10,12,13,20,18,15,14]
y2 = [0.3,0.4,0.5,0.7,1.1,1.3,1.4,2.2,1.6,1.9,1.8]

# 对x1和y1按x值升序排序
sorted_indices = np.argsort(x1)
x1_sorted = np.array(x1)[sorted_indices]
y1_sorted = np.array(y1)[sorted_indices]

# 创建线性插值函数(kind可选'linear'/'cubic'/'quadratic'等)
interp_func = interp1d(x1_sorted, y1_sorted, kind='linear', fill_value="extrapolate")

# 用x2的所有x值插值,得到长度为11的y1_new
y1_new = interp_func(x2)

# 验证结果
print("新的y1数据集(长度11):", y1_new)
print("长度匹配:", len(y1_new) == len(y2))  # 输出True

方法2:使用Numpy内置的interp函数(更简洁)

如果只需要线性插值,Numpy的np.interp函数更轻便,同样需要先排序x1:

import numpy as np

# 原始数据同上,先排序x1和y1
sorted_indices = np.argsort(x1)
x1_sorted = np.array(x1)[sorted_indices]
y1_sorted = np.array(y1)[sorted_indices]

# 直接用np.interp插值
y1_new = np.interp(x2, x1_sorted, y1_sorted)

print("新的y1数据集:", y1_new)
print("长度:", len(y1_new))  # 输出11

额外说明

如果你不想用x2的x值,而是想把x1的区间均匀分成11个点,可以替换成:

# 生成x1区间内的11个均匀点
x1_new = np.linspace(x1_sorted[0], x1_sorted[-1], 11)
y1_new = interp_func(x1_new)  # 或者用np.interp(x1_new, x1_sorted, y1_sorted)

内容的提问来源于stack exchange,提问作者SGhaleb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:07:48