避免循环,在3D numpy数组的维度上进行插值

时间:2014-01-13 15:02:02

标签: python arrays loops numpy 3d

我有一个大的3D numpy维数组(l,n,m),其元素对应于x,y和z的1D数组,分别为l,n和m。我想通过在x和y的每个组合的z值之间进行插值来找到a(具有长度b)的给定值的元素。这将给出尺寸(l,n,b)的输出3D阵列。我想完全使用numpy数组,而不是求助于循环。

例如,如果我的3D数组具有尺寸(2,3,4):

x = 1 | z = 1 | 2 | 3 | 4 
- - - - - - - - - - - - - - 
y = 1 |[[[ 0,  1,  2,  3],       
y = 2 |  [ 4,  5,  6,  7],
y = 3 |  [ 8,  9, 10, 11]],

x = 2 | z = 1 | 2 | 3 | 4 
- - - - - - - - - - - - -
y = 1 | [[ 12, 13, 14, 15],        
y = 2 |  [ 16, 17, 18, 19],
y = 3 |  [ 20, 21, 22, 23]]]

我想在每行{(x = 1,y = 1),(x = 1,y = 2),(x = 1,y = 3),(x = 2,y = 1)进行插值),(x = 2,y = 2),(x = 2,y = 3)}对于a = [1.3,1.8,2.34,2.9,3.45]的值,给出一个三维的维数阵列(2,3, 5):

[[[  0.3,  0.8,  1.34,  1.9,  2.45],
  [  4.3,  4.8,  5.34,  5.9,  6.45],
  [  8.3,  8.8,  9.34,  9.9, 10.45]],

 [[ 12.3, 12.8, 13.34, 13.9, 14.45],
  [ 16.3, 16.8, 17.34, 17.9, 18.45],
  [ 20.3, 20.8, 21.34, 21.9, 22.45]]]

目前我使用for循环迭代x和y的每个组合,并将我的3D数组的行提供给numpy.iterpolate函数并将输出保存到另一个数组中;然而,对于大型阵列,这是非常慢的。

# array is the 3D array with dimensions (l, n, m)
# x, y and z have length l, n and m respectively
# a is the values at which I wish to interpolate at with length b
# new_array is set up with dimensions (l, n, b) 

new_array = N.zeros(len(x)*len(y)*len(a)).reshape(len(x), len(y), len(a))
for i in range(len(x)):
      for j in range(len(y)):
               new_array[i,j,:] = numpy.interpolate(a, z, array[i,j,:])

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您不需要for循环来通过scipy.interpolate.griddata运行数据:

>>> from itertools import product
>>>from scipy.interpolate import griddata

>>> data = np.arange(24).reshape(2, 3, 4)

>>> x = np.arange(1, 3)
>>> y = np.arange(1, 4)
>>> z = np.arange(1, 5)
>>> points = np.array(list(product(x, y, z)))

# This is needed if your x, y and z are not consecutive ints
>>> _, x_idx = np.unique(x, return_inverse=True)
>>> _, y_idx = np.unique(y, return_inverse=True)
>>> _, z_idx = np.unique(z, return_inverse=True)
>>> point_idx = np.array(list(product(x_idx, y_idx, z_idx)))
>>> values = data[point_idx[:, 0], point_idx[:, 1], point_idx[:, 2]]

>>> new_z = np.array( [1.3, 1.8, 2.34, 2.9, 3.45])
>>> new_points = np.array(list(product(x, y, new_z)))
>>> new_values = griddata(points, values, new_points)
>>> new_values.reshape(2, 3, -1)
array([[[  0.3 ,   0.8 ,   1.34,   1.9 ,   2.45],
        [  4.3 ,   4.8 ,   5.34,   5.9 ,   6.45],
        [  8.3 ,   8.8 ,   9.34,   9.9 ,  10.45]],

       [[ 12.3 ,  12.8 ,  13.34,  13.9 ,  14.45],
        [ 16.3 ,  16.8 ,  17.34,  17.9 ,  18.45],
        [ 20.3 ,  20.8 ,  21.34,  21.9 ,  22.45]]])