0

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.

4
  • look at the np.transpose docs Commented Sep 4, 2022 at 14:10
  • @hpaulj thank you. I did, but didn't manage to get desired result. Commented Sep 4, 2022 at 14:16
  • transpose can do the same thing as swapaxes Commented Sep 4, 2022 at 14:33
  • The hstack treats the array as 4 arrays of shape (2,5), and concatenates them on the last dimension. The swapaxes/transpose approach makes a (2,4,5) array, and reshapes that to (2,20). Your attempt made 2 arrays of length 20, and joined them. Commented Sep 4, 2022 at 15:27

2 Answers 2

3

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.]])
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.