1

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

2 Answers2

1

I think what your doing is fine, but for readability I would use

stack = numpy.hstack(rr)

instead of

stack = numpy.column_stack(rr[:,:,:])

Kenan
  • 13,156
  • 8
  • 43
  • 50
1

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.

Andriy Makukha
  • 7,580
  • 1
  • 38
  • 49