Interpolating a 3d array in Python. How to avoid for loops?

前端 未结 2 689
星月不相逢
星月不相逢 2021-01-14 16:47

I have an array which I want to interpolate over the 1st axes. At the moment I am doing it like this example:

import numpy as np
from scipy.interpolate impor         


        
相关标签:
2条回答
  • 2021-01-14 17:12

    Because you're interpolating regularly-gridded data, have a look at using scipy.ndimage.map_coordinates.

    As a quick example:

    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))
    
    0 讨论(0)
  • 2021-01-14 17:22

    You can specify an axis argument to 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)
    

    0 讨论(0)
提交回复
热议问题