how to reshape an N length vector to a 3x(N/3) matrix in numpy using reshape

前端 未结 1 1826
天命终不由人
天命终不由人 2020-12-21 10:51

i have a numpy array of shape (12,). I want to reshape it so that [[1,2,3,4,5,6,7,8,9,10,11,12]] becomes

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


        
相关标签:
1条回答
  • 2020-12-21 11:20

    Reshape to split the first axis into two with the latter of length 3 and transpose -

    a.reshape(-1,3).T
    

    Or reshape in fortran order with reshaping parameters flipped -

    a.reshape(3,-1, order='F')
    

    Sample run -

    In [714]: a
    Out[714]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
    
    In [715]: a.reshape(-1,3).T
    Out[715]: 
    array([[ 1,  4,  7, 10],
           [ 2,  5,  8, 11],
           [ 3,  6,  9, 12]])
    
    In [719]: a.reshape(3,-1, order='F')
    Out[719]: 
    array([[ 1,  4,  7, 10],
           [ 2,  5,  8, 11],
           [ 3,  6,  9, 12]])
    
    0 讨论(0)
提交回复
热议问题