在Python中插入一个3d数组.如何避免for循环?

nic*_*ris 3 python arrays interpolation numpy scipy

我有一个数组,我想插入第一轴.目前我正在这样做:

import numpy as np
from scipy.interpolate import interp1d

array = np.random.randint(0, 9, size=(100, 100, 100))
new_array = np.zeros((1000, 100, 100))
x = np.arange(0, 100, 1)
x_new = np.arange(0, 100, 0.1)

for i in x:
    for j in x:
        f = interp1d(x, array[:, i, j])
        new_array[:, i, j] = f(xnew)
Run Code Online (Sandbox Code Playgroud)

我使用的数据表示域中每个纬度和经度的10年5天平均值.我想创建一个每日值数组.

我也尝试过使用样条线.我真的不知道它们是如何工作的,但速度并不快.

有没有办法在不使用for循环的情况下执行此操作?如果必须使用for循环,还有其他方法可以加快速度吗?

提前感谢您的任何建议.

pv.*_*pv. 7

您可以为interp1d指定一个axis参数:

import numpy as np
from scipy.interpolate import interp1d
array = np.random.randint(0, 9, size=(100, 100, 100))
x = np.linspace(0, 100, 100)
x_new = np.linspace(0, 100, 1000)
new_array = interp1d(x, array, axis=0)(x_new)
new_array.shape # -> (1000, 100, 100)


Joe*_*ton 6

因为您要定期插入网格化数据,所以请看一下使用情况scipy.ndimage.map_coordinates.

作为一个简单的例子:

import numpy as np
import scipy.ndimage as ndimage

interp_factor = 10
nx, ny, nz = 100, 100, 100
array = np.random.randint(0, 9, size=(nx, ny, nz))

# If you're not familiar with mgrid: 
# http://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html
new_indicies = np.mgrid[0:nx:interp_factor*nx*1j, 0:ny, 0:nz]

# order=1 indicates bilinear interpolation. Default is 3 (cubic interpolation)
# We're also indicating the output array's dtype should be the same as the 
# original array's. Otherwise, a new float array would be created.
interp_array = ndimage.map_coordinates(array, new_indicies, 
                                       order=1, output=array.dtype)
interp_array = interp_array.reshape((interp_factor * nx, ny, nz))
Run Code Online (Sandbox Code Playgroud)