Reshaping numpy array and converting columns to rows

Question:

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.

Asked By: Julia

||

Answers:

You can swapaxes and reshape:

sample_array.swapaxes(0, 1).reshape(sample_array.shape[1], -1)

output:

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.]])
Answered By: mozway

I think simple horizontal stack hstack should work fine:

>>> np.hstack(sample_array)

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.]])
Answered By: ThePyGuy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.