将3D Numpy阵列重塑为2D阵列 [英] Reshaping 3D Numpy Array to a 2D array

查看:63
本文介绍了将3D Numpy阵列重塑为2D阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Numpy中具有以下3D阵列:

I have the following 3D array in Numpy:

a = np.array([[[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]],[[13,14],[15,16]]])

我写

b = np.reshape(a, [4,4])

二维结果数组将类似于

 [[ 1  2  3  4]
  [ 5  6  7  8]
  [ 9 10 11 12]
  [13 14 15 16]]

但是,我希望它具有这种形状:

However, I want it to be in this shape:

 [[ 1  2  5  6]
  [ 3  4  7  8]
  [ 9 10 13 14]
  [11 12 15 16]]

如何在Python/Numpy中高效地做到这一点?

How can I do this efficiently in Python/Numpy?

推荐答案

重塑形状以将第一个轴分为两个,排列的轴和另一个重塑形状-

Reshape to split the first axis into two, permute axes and one more reshape -

a.reshape(2,2,2,2).transpose(0,2,1,3).reshape(4,4)
a.reshape(2,2,2,2).swapaxes(1,2).reshape(4,4)

将其设为通用,将变为-

Making it generic, would become -

m,n,r = a.shape
out = a.reshape(m//2,2,n,r).swapaxes(1,2).reshape(-1,2*r)

样品运行-

In [20]: a
Out[20]: 
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],

       [[ 9, 10],
        [11, 12]],

       [[13, 14],
        [15, 16]]])

In [21]: a.reshape(2,2,2,2).swapaxes(1,2).reshape(4,4)
Out[21]: 
array([[ 1,  2,  5,  6],
       [ 3,  4,  7,  8],
       [ 9, 10, 13, 14],
       [11, 12, 15, 16]])

这篇关于将3D Numpy阵列重塑为2D阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆