我想在给定一个固定的 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])
考虑到 arange
d 数据的性质,以及对其进行插值的列 (y
),这是有道理的。
关于python - 对 x 值矩阵中的每一行进行插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30905195/