简体   繁体   中英

Reshaping numpy array and converting columns to rows

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM