Search code examples
pythonnumpyindexingtransformgdal

Shift array to make first and last columns adjacent


I'm struggling how to explain this in the question title so I'll try better here.

I have an array which contains 360 columns and 180 rows which represents each degree of latitude and longitude on earth. For clarity, my data looks like the following:

longitudes = [0, 1, 2 ... 358, 359]
latitudes = [90, -89 ... -89, -90]
data = np.random.randint(5, (180, 360))

It looks like this, where longitude '0' is equal to 0E and '359' is equal to -1E.

As you can see, Africa is split at the start and end of the array and I would like to shift the array so that the first columns corresponds to -180E and the last columns corresponds to 180E, like the traditional world view (map) - this will make subsetting the array to 'cookie cut' Africa out.

How do I shift/transform my array so that the first and last column are adjacent?

(Extra: since you can think of my array as a cylinder, as geographically, the first and last rows are adjacent, but how do I change where the 'cylinder is cut' - the analogy I've been thinking of)


Solution

  • Solution was to use numpy.roll().

    I firstly found the index of the column corresponding to 180E using:

    idx = (longitude.index(180))
    

    Then, I 'rolled' the data based on this index to move 180E to the furthest left column using:

    rolled_data = np.roll(data, idx, axis=1)
    

    This successfully centred the 0E column to create my desired output.