Python row major to column major order vector

后端 未结 4 1113
情歌与酒
情歌与酒 2020-12-10 20:02

Having a matrix like

ma = [[0.343, 0.351, 0.306], [0.145, 0.368, 0.487]]

I want to get a vector like:

[0.343, 0.145, 0.351,         


        
相关标签:
4条回答
  • 2020-12-10 20:43

    Flatten the array in Fortran order:

    c = a.flatten(order='F')
    

    You could also get the results you wanted with reshape, but it's wordier:

    c = a.reshape(a.size, order='F')
    
    0 讨论(0)
  • 2020-12-10 20:48

    You can get want you want by transposing the matrix and then using numpy's ravel function:

    mat = np.random.rand(3,2)
    print np.ravel(mat.T)
    
    0 讨论(0)
  • 2020-12-10 20:58

    You can use ravel() to flatten the array.

    >>> a.T.ravel()
    array([ 0.343,  0.145,  0.351,  0.368,  0.306,  0.487])
    
    # Or specify Fortran order.
    >>> a.ravel('F')
    array([ 0.343,  0.145,  0.351,  0.368,  0.306,  0.487])
    
    a = np.random.rand(4,2)
    >>> a
    array([[ 0.59507926,  0.25011282],
           [ 0.68171766,  0.41653172],
           [ 0.83888691,  0.22479481],
           [ 0.04540208,  0.23490886]])
    
    >>> a.T.ravel()  # or a.ravel('F')
    array([ 0.59507926,  0.68171766,  0.83888691,  0.04540208,  0.25011282,
            0.41653172,  0.22479481,  0.23490886])
    
    0 讨论(0)
  • 2020-12-10 21:02
    >>> A = ([[0, 1, 2],
    ...        [3, 4, 5],
    ...        [6, 7, 8]])
    >>> 
    >>> print(A)
    [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
    >>> 
    >>> [y  for x in [[row[i] for row in A] for i in range(len(A[0]))] for y in x]
    [0, 3, 6, 1, 4, 7, 2, 5, 8]
    >>> 
    >>> 
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题