python - 重新排列 numpy 数组

标签 python numpy

import numpy as np
a = np.array([[1,2],
              [3,4],
              [5,6],

             [7,8],
             [9,10],
             [11,12]])
print np.shape(a)

预期的答案应该是:

answer = np.array([[1,2,7,8],
              [3,4, 9, 10],
              [5,6, 11, 12]])

我尝试过

ans = a.reshape(3,-1)    
print ans

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

但是答案是错误的。怎么做?

最佳答案

您可以使用一些轴的 reshape 和交换,就像这样 -

L = 3 # Cutting length
out = a.reshape(-1,L,a.shape[1]).swapaxes(0,1).reshape(L,-1)

或者使用np.transpose来交换轴,就像这样 -

out = a.reshape(-1,L,a.shape[1]).transpose(1,0,2).reshape(L,-1)

关于python - 重新排列 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36943700/

相关文章:

python - 顺序排列

python - 属性错误 : 'bytes' object has no attribute 'find_all' after encoding in Python

python - 在 Spyder 中对缩进级别/视觉指示进行颜色编码

python - 用自定义数据类型就地替换数组的 numpy 数组值

python - 导入cv2时出错: 'libSM.so.6: cannot open shared object file: No such file or directory'

python / Pandas : Unexpected indices when doing a groupby-apply

python - 使用字典对 NumPy 数组进行切片

python - 在 python 中绘制轨道轨迹

python - 数组的按列归一化(缩放)

python - 如何使用 pyparsing 对放置在不同位置的标记进行分组?