简体   繁体   English

如何使用整形将N长度向量整形为numpy中的3x(N / 3)矩阵

[英]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,). 我有一个形状为(12,)的numpy数组。 I want to reshape it so that [[1,2,3,4,5,6,7,8,9,10,11,12]] becomes 我想重塑它,使[[1,2,3,4,5,6,7,8,9,10,11,12]]变为

 [[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. 我尝试了a.reshape(3,4)和a.reshape(-1,4),但是没有任何东西可以产生我想要的东西。 is there a simple way of doing this or do i need to create a new array and set each value individually? 有没有一种简单的方法可以做到这一点,还是我需要创建一个新数组并分别设置每个值?

Reshape to split the first axis into two with the latter of length 3 and transpose - 重塑形状以将第一个轴分为长度为3两个轴并转置-

a.reshape(-1,3).T

Or reshape in fortran order with reshaping parameters flipped - 或以翻转格式参数的形式按fortran顺序进行重塑-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM