Home > Enterprise >  Reshape 2D numpy array into 3 1D arrays with x,y indices
Reshape 2D numpy array into 3 1D arrays with x,y indices

Time:12-20

I have a numpy 2D array (50x50) filled with values. I would like to flatten the 2D array into one column (2500x1), but the location of these values are very important. The indices can be converted to spatial coordinates, so I want another two (x,y) (2500x1) arrays so I can retrieve the x,y spatial coordinate of the corresponding value.

For example:

My 2D array: 
--------x-------
[[0.5 0.1 0. 0.] |
 [0. 0. 0.2 0.8] y
 [0. 0. 0. 0. ]] |

My desired output: 
#Values
[[0.5]
 [0.1]
 [0. ]
 [0. ]
 [0. ]
 [0. ]
 [0. ]
 [0.2]
 ...], 
#Corresponding x index, where I will retrieve the x spatial coordinate from
[[0]
 [1]
 [2]
 [3]
 [4]
 [0]
 [1]
 [2]
 ...], 
#Corresponding y index, where I will retrieve the x spatial coordinate from
[[0]
 [0]
 [0]
 [0]
 [1]
 [1]
 [1]
 [1]
 ...], 

Any clues on how to do this? I've tried a few things but they have not worked.

CodePudding user response:

Assuming you want to flatten and reshape into a single column, use reshape:

a = np.array([[0.5, 0.1, 0., 0.],
              [0., 0., 0.2, 0.8],
              [0., 0., 0., 0. ]])

a.reshape((-1, 1)) # 1 column, as many row as necessary (-1)

output:

array([[0.5],
       [0.1],
       [0. ],
       [0. ],
       [0. ],
       [0. ],
       [0.2],
       [0.8],
       [0. ],
       [0. ],
       [0. ],
       [0. ]])
getting the coordinates
y,x = a.shape
np.tile(np.arange(x), y)
# array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3])
np.repeat(np.arange(y), x)
# array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2])

CodePudding user response:

For the simplisity let's reproduce your array with this chunk of code:

value = np.arange(6).reshape(2, 3)

Firstly, we create variables x, y which contains index for each dimension:

x = np.arange(value.shape[0])
y = np.arange(value.shape[1])

np.meshgrid is the method, related to the issue you described:

xx, yy = np.meshgrid(x, y, sparse=False)

Finaly, transform all elements it in the shape you want with these lines:

xx = xx.reshape(-1, 1)
yy = yy.reshape(-1, 1)
value = value.reshape(-1, 1)

CodePudding user response:

According to your example, with np.indices:

data = np.arange(2500).reshape(50, 50)
y_indices, x_indices = np.indices(data.shape)

Reshaping your data:

data = data.reshape(-1,1)
x_indices = x_indices.reshape(-1,1)
y_indices = y_indices.reshape(-1,1)

  • Related