I am sorry for the vagueness of the heading. I have the following task that I can't seem to solve. I have an array of shape (4,2,k). I want to reshape it to shape (2,k*4) while converting columns to rows.
Here is a sample input array where k=5:
sample_array = array([[[2., 2., 2., 2., 2.],
[1., 1., 1., 1., 1.]],
[[2., 2., 2., 2., 2.],
[1., 1., 1., 1., 1.]],
[[2., 2., 2., 2., 2.],
[1., 1., 1., 1., 1.]],
[[2., 2., 2., 2., 2.],
[1., 1., 1., 1., 1.]]])
I have managed to get desired output with a for-loop
twos=np.array([])
ones=np.array([])
for i in range(len(sample_array)):
twos = np.concatenate([twos, sample_array[i][0]])
ones = np.concatenate([ones, sample_array[i][1]])
desired_array = np.array([twos, ones])
where desired array looks like this:
array([[2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,
2., 2., 2., 2.],
[1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 1.]])
Is there a more elegant solution to my task? I have tried .reshape(), .transpose(), .ravel() but never seem to get the desired outcome.
I am sorry if this is a duplicate, I have looked through a few dozen StackOverflow Qs but found no solution.
np.transposedocstransposecan do the same thing asswapaxeshstacktreats the array as 4 arrays of shape (2,5), and concatenates them on the last dimension. Theswapaxes/transposeapproach makes a (2,4,5) array, and reshapes that to (2,20). Your attempt made 2 arrays of length 20, and joined them.