首页 > 解决方案 > 在列块中展平或分组数组 - NumPy / Python

问题描述

有什么简单的方法可以压扁

import numpy    
np.arange(12).reshape(3,4)
Out[]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

进入

array([ 0,  1,  4,  5, 8, 9, 2, 3, 6, 7, 10, 11])

标签: pythonnumpyflatten

解决方案


似乎您正在考虑考虑特定数量的 cols 来形成块,然后获取每个块中的元素,然后移动到下一个块中。因此,考虑到这一点,这是一种方法 -

In [148]: a
Out[148]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [149]: ncols = 2 # no. of cols to be considered for each block

In [150]: a.reshape(a.shape[0],-1,ncols).swapaxes(0,1).ravel()
Out[150]: array([ 0,  1,  4,  5,  8,  9,  2,  3,  6,  7, 10, 11])

背后的动机在 中详细讨论this post

此外,为了保持 2D 格式 -

In [27]: a.reshape(a.shape[0],-1,ncols).swapaxes(0,1).reshape(-1,ncols)
Out[27]: 
array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [ 2,  3],
       [ 6,  7],
       [10, 11]])

并以直观的3D 数组格式显示它 -

In [28]: a.reshape(a.shape[0],-1,ncols).swapaxes(0,1)
Out[28]: 
array([[[ 0,  1],
        [ 4,  5],
        [ 8,  9]],

       [[ 2,  3],
        [ 6,  7],
        [10, 11]]])

推荐阅读