如何从 Numpy 数组中查找(插入)多个值

How to lookup (interpolate) several values from Numpy Array

我需要一个函数来根据另一个值(在本例中为时间)从数组中查找 多个值 。 这也可以被认为是“先前值插值”。 这只适用于 Matlab/Octave:

inputArray = [3600, 60, 50, 40; 3700, 0, 50, 40; 7260, 200, 20, 10];
t_current   = 3650;
inputVector = interp1(inputArray(:,1), inputArray(:, 2:end), t_current, 'previous', 0)

并给予

inputVector =

   60   50   40

符合预期。如何在 Python 中完成?

以下工作,但相当笨拙,因为我需要为 inputArray!

的每一列重复 interp1d 命令
import numpy as np
from scipy.interpolate import interp1d

# Time, q_in, x_in, y_in
inputArray  = np.array(([3600, 60, 50, 40], [3700, 0, 50, 40], [7260, 200, 20, 10]))
t_current   = 3650

itp_q_in    = interp1d(inputArray[:,0], inputArray[:,1], kind='previous', \
                    bounds_error=False, fill_value=(0, 0))  # Works
# Repeat for each column(!!!)
itp_x_in    = interp1d(inputArray[:,0], inputArray[:,2], kind='previous', \
                    bounds_error=False, fill_value=(0, 0))
itp_y_in    = interp1d(inputArray[:,0], inputArray[:,3], kind='previous', \
                    bounds_error=False, fill_value=(0, 0))
# Throws ValueError: x and y arrays must be equal in length along interpolation axis.
#itp_qxy_in  = interp1d(inputArray[:,0], inputArray[:,1:], kind='previous', \
#                    bounds_error=False, fill_value=(0, 0))

inputVector = np.array([itp_q_in(t_current), itp_x_in(t_current), itp_y_in(t_current)])

并给予

inputVector
    array([60., 50., 40.])

有没有更紧凑的版本来写这个?我的真实 inputArray 可能很容易就有 50 列!!!

scipy 函数支持与 Matlab 函数完全相同的功能,语法完全相同。来自 docs:

y: (…,N,…) array_like

A N-D array of real values. The length of y along the interpolation axis must be equal to the length of x.

在代码中(注意 axis=0 参数):

>>> interp1d(inputArray[:,0], inputArray[:,1:], kind='previous', axis=0)(t_current)
array([60., 50., 40.])

您的 itp_qxy_in 抛出的错误非常明确。发生这种情况的原因是因为 axis 参数默认为 -1,因此将沿列进行插值。这当然是在您可能有 50 列的实际代码中。在你的玩具示例中,inputArray[:,1:] 恰好是一个 3x3 数组,它会很高兴地沿着任一轴积分(当然 axis=-1 仍然会给出错误的结果)。

编辑:

Matlab 和 numpy 有不同的数组布局。前者是列专业,后者是行专业。最好将您的数据转换为您在 Matlab 中实际键入它们的方式。然后 axis=-1 论点变得更自然。

a = inputArray.T
interp1d(a[0], a[1:], kind='previous')(t_current)