numpymachine-learningreshape

Numpy reshape() to display 2D array in 3D programmatically


Example Data

I have an array of weather data by lat/lon in the following shape: (1038240,4) (See photo for sample example data)

I want to reshape this to the shape (4,721,1440) which would be four weather variables (& lat/lon) over a 721 by 1440 image of the globe.

I have tried:

newarr = t_new.reshape(4,721,1440) 

which puts this in the correct shape, but doesn't match this to the first two lat/lon coordinates to the preferred format below:

For the (6,4) example data in the photo above, this operation would look like a (2,3,2) array below:

Example Desired Output

newarr = t_new.reshape(4,721,1440) 

Solution

  • Further investigation reveals that numpy.reshape() operates in row-major (C-style) order by default, which means it fills the new array along the last axis first (i.e., from left to right, top to bottom)

    So if I reshape this first then transpose:

    reshaped = t_new.reshape((1440, 721, 6))  # Reshape to (1440, 721, 4)
    correct_order = reshaped.transpose((2, 1, 0))  # Swap axes to get (4, 721, 1440)
    

    It seems to produce the desired output. I test this by looking at the slices to see that longitude/latitude are constant along each slice:

    correct_order[:,:,1]
    correct_order[:,1,:]
    

    Thanks to comments from hpaulj for hint to transpose this.