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

前端 未结 6 683
醉酒成梦
醉酒成梦 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

    You can use a list comprehension to slice the array into blocks and then use the numpy.ndarray.flatten method to flatten the blocks into a 1D array (this will only work if a.shape[1] is divisible by the block size n):

    import numpy as np
    
    a = np.arange(12).reshape(3, 4)
    
    n = 2
    
    res = np.array([a[:, i : i + n] for i in range(0, a.shape[1], n)]).flatten()
    
    print(res)
    

    Output:

    [ 0  1  4  5  8  9  2  3  6  7 10 11 ]
    

提交回复
热议问题