Flatten or group array in blocks of columns - NumPy / Python

前端 未结 6 660
醉酒成梦
醉酒成梦 2020-12-04 03:00

Is there any easy way to flatten

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


        
6条回答
  •  一生所求
    2020-12-04 03:31

    It seems like you are looking to consider a specific number of cols to form blocks and then getting the elements in each block and then moving onto the next ones. So, with that in mind, here's one way -

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

    The motivation behind is discussed in detail in this post.

    Additionally, to keep the 2D format -

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

    And to have it in a intuitive 3D array format -

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

提交回复
热议问题