python - 对 x 值矩阵中的每一行进行插值

标签 python numpy scipy interpolation

我想在给定一个固定的 y 值向量的情况下,在矩阵的每一行(x 值)的值之间进行插值。我正在使用 python,本质上我需要类似 scipy.interpolate.interp1d 的东西,但 x 值是矩阵输入。我通过循环实现了这一点,但我希望操作尽可能快。

编辑

下面是我现在正在做的代码示例,请注意我的矩阵有数百万行:

import numpy as np
x = np.linspace(0,1,100).reshape(10,10)
results = np.zeros(10)
for i in range(10):
  results[i] = np.interp(0.1,x[i],range(10))

最佳答案

正如@Joe Kington 所建议的,您可以使用 map_coordinates :

import scipy.ndimage as nd

# your data - make sure is float/double
X = np.arange(100).reshape(10,10).astype(float)

# the points where you want to interpolate each row 
y = np.random.rand(10) * (X.shape[1]-1)
# the rows at which you want the data interpolated -- all rows
r = np.arange(X.shape[0])

result = nd.map_coordinates(X, [r, y], order=1, mode='nearest')

以上,对于以下y:

array([ 8.00091648,  0.46124587,  7.03994936,  1.26307275, 1.51068952,
        5.2981205 ,  7.43509764,  7.15198457,  5.43442468,  0.79034372])

请注意,每个值都表示要为每一行插入值的位置。

给出以下结果:

array([  8.00091648,  10.46124587,  27.03994936,  31.26307275,
        41.51068952,  55.2981205 ,  67.43509764,  77.15198457,
        85.43442468,  90.79034372])

考虑到 aranged 数据的性质,以及对其进行插值的列 (y),这是有道理的。

关于python - 对 x 值矩阵中的每一行进行插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30905195/

相关文章:

python - 散点图同一点重复多次python

python - RabbitMQ 错误 530 vhost 未与 pika 一起找到

python - 如何查找 Pandas 中组总数的百分比

python - 将 Pandas 系列和数据框对象转换为 numpy 数组

python - 更有效地检测支票(国际象棋)

python - 相当于基本 python 中的 Numpy.argsort()?

python - 通过 scipy.integrate.ode 使用自适应步长

python - 如何使用 scipy.integrate.odeint 求解具有时间相关变量的 ODE 系统

python:将(字符串)集列表转换为 scipy csr_matrix

python - 隔离林实现