简体   繁体   English

重塑 numpy 数组并将列转换为行

[英]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) .我有一个形状数组(4,2,k) I want to reshape it to shape (2,k*4) while converting columns to rows.我想在将列转换为行时将其重塑为形状(2,k*4)

Here is a sample input array where k=5:这是一个示例输入数组,其中 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我已经设法通过for-loop获得所需的 output

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

Is there a more elegant solution to my task?我的任务有更优雅的解决方案吗? I have tried.reshape(), .transpose(), .ravel() but never seem to get the desired outcome.我尝试过.reshape()、.transpose()、.ravel(),但似乎从来没有得到想要的结果。

I am sorry if this is a duplicate, I have looked through a few dozen StackOverflow Qs but found no solution.如果这是重复的,我很抱歉,我查看了几十个 StackOverflow Q,但没有找到解决方案。

You can swapaxes and reshape :您可以swapaxesreshape

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

output: 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:我认为简单的水平堆栈hstack应该可以正常工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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