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

前端 未结 2 688
星月不相逢
星月不相逢 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))
    

提交回复
热议问题