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

如何沿指定轴对二维数组线性插值?(scipy报错解决)

二维数组沿axis=1批量插值的解决方案

问题重现

尝试使用scipy.interpolate.interp1d沿axis=1对二维数组插值时触发报错,代码及错误信息如下:

import numpy as np
import scipy.interpolate

xp = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
               [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]])
yp = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
               [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]])

x = np.array([[1.5, 4.5, 7.5],
              [2.5, 6.5, 9.5]])

interpolate = scipy.interpolate.interp1d(xp, yp, axis=1)
# ValueError: x and y arrays must be equal in length along interpolation axis.

预期输出:

[[ 1.5  4.5  7.5]
 [ 6.5 42.5 90.5]]

实际数组规模较大,希望避免逐行循环处理。

报错原因

scipy.interpolate.interp1d要求插值轴上的x输入为一维数组,或所有行的x样本点完全一致且以一维形式传入。若传入二维的xp,函数会将其视为两组独立的x样本序列,此时xp在axis=1的长度为11,而待插值的x在axis=1的长度为3,二者长度不匹配,因此触发ValueError。

解决方案

由于示例中所有行的xp样本点完全一致,只需将xp转为一维数组,即可利用interp1d的广播特性实现批量插值,无需循环:

import numpy as np
from scipy.interpolate import interp1d

# 将xp改为一维数组(所有行样本点一致)
xp = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
yp = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
               [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]])
x = np.array([[1.5, 4.5, 7.5],
              [2.5, 6.5, 9.5]])

# 初始化插值函数,指定axis=1沿列方向插值
f = interp1d(xp, yp, axis=1)
# 批量计算插值结果
result = f(x)

print(result)

运行后输出与预期完全一致:

[[ 1.5  4.5  7.5]
 [ 6.5 42.5 90.5]]

拓展场景(若每行xp不同)

如果每行的xp样本点不一致,可使用scipy.interpolate.interpn结合数组维度调整实现批量处理,或使用numba加速循环(效率优于原生Python循环)。但针对当前场景,上述方案已足够高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:05:33