如何插入包含数组的列表?

2024-04-16 08:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在两个列表之间插值,其中第一个包含数字,第二个包含数组。你知道吗

我试着从scipy使用interp1d,但没有成功

    from scipy import interpolate

    r = [2,3,4]
    t = [5,6,7]
    f = [r,t]
    q = [10,20]
    c = interpolate.interp1d(q, f)

我想得到一个数组,比如值15,它应该是r和t数组之间的插值

错误消息:

    ValueError: x and y arrays must be equal in length along interpolation axis.

Tags: andfromimport消息列表错误数字scipy
2条回答

下面是指向scipy文档interpolate SciPy中interp1d函数的链接。 从文档中可以看到,该函数不接受列表列表作为输入。输入需要是numpy数组或原语值列表。你知道吗

在OP的简单例子中,采用1D还是2D插值并没有区别。然而,如果更多的向量起作用,就会产生不同的效果。这里两个选项,使用numpy和处理浮点。你知道吗

from scipy.interpolate import interp1d
from scipy.interpolate import interp2d
import numpy as np
r = np.array( [ 1, 1, 2], np.float )
s = np.array( [ 2, 3, 4], np.float )
t = np.array( [ 5, 6, 12], np.float ) # length of r,s,t,etc must be equal
f = np.array( [ r, s, t ] )
q = np.array( [ 0, 10, 20 ], np.float )  # length of q is length of f


def interpolate_my_array1D( x, xData, myArray ):
    out = myArray[0].copy()
    n = len( out )
    for i in range(n):
        vec = myArray[ : , i ]
        func = interp1d( xData, vec )
        out[ i ] = func( x )
    return out


def interpolate_my_array2D( x, xData, myArray ):
    out = myArray[0].copy()
    n = len( out )
    xDataLoc = np.concatenate( [ [xx] * n for xx in xData ] )
    yDataLoc = np.array( range( n ) * len( xData ), np.float )
    zDataLoc = np.concatenate( myArray )
    func = interp2d( xDataLoc, yDataLoc, zDataLoc )
    out = np.fromiter( ( func( x, yy ) for yy in range(n) ), np.float )
    return out

print interpolate_my_array1D( 15., q, f )
print interpolate_my_array2D( 15., q, f )

给予

>> [3.5 4.5 5.5]
>> [2.85135135 4.17567568 6.05405405]

相关问题 更多 >