Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

numpy - Python row major to column major order vector

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...