如何将 numpy 矩阵从 2D 重塑为 3D 列?

How to reshape a numpy matrix from 2D to 3D column-wise?

我不明白 Python 中 numpy 中的 reshape 函数。我遇到了以下问题:

我想重塑 (6, 2) 数组

A = np.c_[np.arange(1, 7), np.arange(6, 12)]

这是

array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10],
       [ 6, 11]])

变成(2, 3, 2)数组,如

array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])

我试过了

np.reshape(A, (2, 3, 2), order='F')

但结果不是我想要的。相反,它是:

array([[[ 1,  6],
        [ 3,  8],
        [ 5, 10]],

       [[ 2,  7],
        [ 4,  9],
        [ 6, 11]]])

这里有两个问题:

  1. 你要的形状其实是(2, 2, 3),不是(2, 3, 2)
  2. order="F" 并不像您想象的那样。您真正想要的是使用 A.T.
  3. 转置数组

此外,您可以使用 A.reshape(...) 而不是 np.reshape(A, ...)

代码如下:

import numpy as np

A = np.c_[np.arange(1,7), np.arange(6,12)]
print(A)
print("\n->\n")
print(A.T.reshape((2, 2, 3)))

给出:

array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10],
       [ 6, 11]])

->

array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])

order="F".T

的解释

尝试A.ravel(order="F")看看数组的元素是"F"的顺序。您将获得:

array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10],
       [ 6, 11]])

->

array([ 1,  2,  3,  4,  5,  6,  6,  7,  8,  9, 10, 11])

现在,如果您在此之后应用正常的 order,您将得到预期的结果:

A.ravel(order="F").reshape((2, 2, 3)) -> 

array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])

问题是,order="F" 也会影响将拼凑的元素添加回数组的方式。不仅元素被取出 column-wise,它们也被添加回 column-wise。所以:

[[[], []], [[], []]] -> 
[[[1], []], [[], []]] -> 
[[[1], []], [[2], []]] -> 
[[[1], [3]], [[2], []]] -> 
[[[1], [3]], [[2], [4]]] -> 
[[[1, 5], [3]], [[2], [4]]] -> 
[[[1, 5], [3]], [[2, 6], [4]]] -> 
[[[1, 5], [3, 7]], [[2, 6], [4]]] -> 
[[[1, 5], [3, 6]], [[2, 6], [4, 7]]] -> 
[[[1, 5, 8], [3, 6]], [[2, 6], [4, 7]]] -> 
[[[1, 5, 8], [3, 6]], [[2, 6, 9], [4, 7]]] -> 
[[[1, 5, 8], [3, 6, 10]], [[2, 6, 9], [4, 7]]] -> 
[[[1, 5, 8], [3, 6, 10]], [[2, 6, 9], [4, 7, 11]]]

:

[[[1], []], [[], []]] -> 
[[[1, 2], []], [[], []]] -> 
[[[1, 2, 3], []], [[], []]] -> 
[[[1, 2, 3], [4]], [[], []]] -> 
[[[1, 2, 3], [4, 5]], [[], []]] -> 
[[[1, 2, 3], [4, 5, 6]], [[], []]] -> 
[[[1, 2, 3], [4, 5, 6]], [[6], []]] -> 
[[[1, 2, 3], [4, 5, 6]], [[6, 7], []]] -> 
[[[1, 2, 3], [4, 5, 6]], [[6, 7, 8], []]] -> 
[[[1, 2, 3], [4, 5, 6]], [[6, 7, 8], [9]]] -> 
[[[1, 2, 3], [4, 5, 6]], [[6, 7, 8], [9, 10]]] -> 
[[[1, 2, 3], [4, 5, 6]], [[6, 7, 8], [9, 10, 11]]]

因此,您最终得到了一个奇怪的结果。如果你只是想用 order="F" 取出元素而不是用那种方式把它们加回去,转置数组会有同样的效果。