arraysnumpysliceaxestiling

Numpy.tile() "confusing" axes on sliced array


I have a 2D numpy array that I have retrieved by slicing a 3D rasterio data set (i.e. I retrieved the first raster band). Now, when I try to tile this 2D numpy array into a 3D array in order to run some vectorized operations, numpy seems to interpret the axes of my array as (1,2) (which were the original axis labels) instead of (0,1).

Let's assume the raster dataset has the shape (1,20,20). I want to retrieve the 2D array stored in axes (1,2), so I slice it like so:

raster_band = raster_data[0,:,:]

Trying to tile this into a tensor of the shape (20,20,4), like this:

tensor = np.tile(raster_band, (1,1,4))

returns a tensor of the shape (1,20,80) instead of the expected outcome.

I've tried variations of flatten and squeeze but nothing solved this for me. Does anyone know a smart way to handle this behaviour?


Solution

  • You need to make it 3D before tiling:

    tensor = np.tile(raster_band[...,None], (1, 1, 4))
    

    Full example:

    raster_data = np.arange(400).reshape((1, 20, 20))
    raster_band = raster_data[0,:,:]
    tensor = np.tile(raster_band[..., None], (1, 1, 4))
    tensor.shape
    # (20, 20, 4)