I have a (2x3) raster file with the following values:
-5-6
-4-5
-1-2
Normally the .xyz GIS file format would be column organised represented by the following numpy array: (coordinates are lower left corner)
col = numpy.array([[0,0,-1],[1,0,-2],[0,1,-3],[1,1,-4],[0,2,-5],[1,2,-6]])
Unfortunately I have a row organized structure (from this data comes from https://www.opengeodata.nrw.de/). It can be represented by the following numpy array:
row = numpy.array([[0,0,-1],[0,1,-3],[0,2,-5],[1,0,-2],[1,1,-4],[1,2,-6]])
print (row)
[[ 0 0 -1]
[ 0 1 -3]
[ 0 2 -5]
[ 1 0 -2]
[ 1 1 -4]
[ 1 2 -6]]
I need to rearrange this row array into a col array. I am currently using this code:
rr = row.reshape(2,3,3)
stack = numpy.column_stack(rr[:,:,:])
new_col =(stack.reshape(-1,3))
print (new_col)
[[ 0 0 -1]
[ 1 0 -2]
[ 0 1 -3]
[ 1 1 -4]
[ 0 2 -5]
[ 1 2 -6]]
This works but my question: Is this the best way to tackle this array transformation? I have little experience manipulation numpy arrays. Thanks Nicolas
You can use transpose method to rearrange the axes.
import numpy
col = numpy.array([[0,0,-1],[1,0,-2],[0,1,-3],[1,1,-4],[0,2,-5],[1,2,-6]])
row = numpy.array([[0,0,-1],[0,1,-3],[0,2,-5],[1,0,-2],[1,1,-4],[1,2,-6]])
# New solution
new_col = row.reshape(2,3,3).transpose(1,0,2).reshape(-1,3)
print(numpy.array_equal(col, new_col))
It works faster than via using column_stack
or hstack
.