Python row major to column major order vector

こ雲淡風輕ζ 提交于 2019-12-17 20:27:32

问题


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, 0.368, 0.306, 0.487]

To try to get it, I am using numpy and reshape but it is not working.

a = np.array(ma)
>>> print a.shape
(2, 3)

But I am getting:

c = a.reshape(3, 2, order='F')
>>> print c
array([[ 0.343,  0.368],
       [ 0.145,  0.306],
       [ 0.351,  0.487]])

What would be the best way to do it for any matrix size? I mean, for example, if matrix is not squared like:

[[0.404, 0.571, 0.025],
 [0.076, 0.694, 0.230],
 [0.606, 0.333, 0.061],
 [0.595, 0.267, 0.138]]

I would like to get:

[0.404, 0.076, 0.606, 0.595, 0.571, 0.694, 0.333, 0.267, 0.025, 0.230, 0.061, 0.138]

回答1:


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



回答2:


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)



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/33030195/python-row-major-to-column-major-order-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!