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
341 views
in Technique[技术] by (71.8m points)

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

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

I have tried a.reshape(3,4) and a.reshape(-1,4) but nothing is producing what i want. is there a simple way of doing this or do i need to create a new array and set each value individually?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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

...