如何使用 reshape 在 numpy 中将 N 长度向量重塑为 3x(N/3) 矩阵 [英] how to reshape an N length vector to a 3x(N/3) matrix in numpy using reshape

查看:30
本文介绍了如何使用 reshape 在 numpy 中将 N 长度向量重塑为 3x(N/3) 矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为 (12,) 的 numpy 数组.我想重塑它,以便[[1,2,3,4,5,6,7,8,9,10,11,12]]变成

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

我尝试了 a.reshape(3,4) 和 a.reshape(-1,4) 但没有产生我想要的.有没有一种简单的方法可以做到这一点,还是我需要创建一个新数组并单独设置每个值?

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?

推荐答案

Reshape 将第一个轴一分为二,后者的长度为 3 并转置 -

Reshape to split the first axis into two with the latter of length 3 and transpose -

a.reshape(-1,3).T

或者按照 fortran 顺序进行整形,并翻转整形参数 -

Or reshape in fortran order with reshaping parameters flipped -

a.reshape(3,-1, order='F')

样品运行 -

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

这篇关于如何使用 reshape 在 numpy 中将 N 长度向量重塑为 3x(N/3) 矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆