【问题标题】:Interpolating a 3d array in Python. How to avoid for loops?在 Python 中插入一个 3d 数组。如何避免for循环?
【发布时间】:2011-10-13 14:40:29
【问题描述】:

我有一个数组,我想在第一个轴上进行插值。目前我正在这样做:

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)

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

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

有没有办法在不使用 for 循环的情况下做到这一点? 如果必须使用 for 循环,还有其他方法可以加快速度吗?

提前感谢您的任何建议。

【问题讨论】:

    标签: python arrays numpy scipy interpolation


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 好点!如果 OP 想要真正的 1D 插值(而不是双线性),那么这就是要走的路。
    • 这也很好用。谢谢!有趣的是(至少在这种情况下)这种方法导致插值数组的平均值更接近原始数组的平均值。
    【解决方案2】:

    因为您正在插入定期网格化的数据,请查看使用 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))
    

    【讨论】:

    • 非常感谢,它看起来会起作用。它适用于掩码数组吗?
    • 编辑:非常感谢,看起来效果很好。我将它与一个掩码数组一起用作要插值的数组。这会使事情复杂化吗?如果我设置 output= array.dtype 会有一个奇怪的结果,但如果我将输出保留为默认值,它似乎工作正常。
    猜你喜欢
    • 2018-08-02
    • 2014-02-01
    • 2022-01-04
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2017-08-27
    • 2017-11-11
    相关资源
    最近更新 更多