Home > Software design >  Reshaping numpy array and converting columns to rows
Reshaping numpy array and converting columns to rows

Time:09-05

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.

CodePudding user response:

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.]])

CodePudding user response:

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.]])
  • Related