Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何通过重新排序重塑numpy阵列?_Python_Numpy - Fatal编程技术网

Python 如何通过重新排序重塑numpy阵列?

Python 如何通过重新排序重塑numpy阵列?,python,numpy,Python,Numpy,我有一个1 x 2 x 3阵列: >>> a = np.array([[[1,2,3],[4,5,6]]]) >>> a array([[[1, 2, 3], [4, 5, 6]]]) >>> a.shape (1, 2, 3) 我想将其重塑为(3,1,2),但使原始dim 3上的元素现在沿dim 1。我希望结果如下所示: >>> new_a array([[[1, 4]], [[2, 5]]

我有一个1 x 2 x 3阵列:

>>> a = np.array([[[1,2,3],[4,5,6]]])
>>> a
array([[[1, 2, 3],
        [4, 5, 6]]])
>>> a.shape
(1, 2, 3)
我想将其重塑为(3,1,2),但使原始dim 3上的元素现在沿dim 1。我希望结果如下所示:

>>> new_a
array([[[1, 4]],
       [[2, 5]],
       [[3, 6]]])
当我只使用“重塑”时,我得到了正确的形状,但元素顺序相同,不是我想要的:

>>> a.reshape((3,1,2))
array([[[1, 2]],
       [[3, 4]],
       [[5, 6]]])
如何实现这一点?

只需使用-

样本运行-

In [347]: a
Out[347]: 
array([[[1, 2, 3],
        [4, 5, 6]]])

In [348]: a.transpose(2,0,1)
Out[348]: 
array([[[1, 4]],

       [[2, 5]],

       [[3, 6]]])
或者:

与-

与-


有几种方法,但是
transpose()
可能是最简单的:

array.transpose(2,0,1)
导入einops
重新排列(x,'XYZ->ZXY')
最好使用一些有意义的轴名称,而不是
x
y
z
(如宽度、高度等)

np.moveaxis(a,2,0)
np.rollaxis(a,2,0)
array.transpose(2,0,1)