Numpy 数组 - 使用重塑将多列堆叠为一列

Numpy array - stack multiple columns into one using reshape

对于这样的二维数组:

table = np.array([[11,12,13],[21,22,23],[31,32,33],[41,42,43]])

是否可以在 table 上使用 np.reshape 得到一个数组 single_column,其中 table 的每一列都是垂直堆叠的?这可以通过拆分 table 并与 vstack.

合并来实现
single_column = np.vstack(np.hsplit(table , table .shape[1]))

Reshape 可以将所有行合并为一行,我想知道它是否也可以合并列以使代码更简洁、可能更快。

single_row = table.reshape(-1)

您可以先转置,再整形:

table.T.reshape(-1, 1)

array([[11],
       [21],
       [31],
       [41],
       [12],
       [22],
       [32],
       [42],
       [13],
       [23],
       [33],
       [43]])

还有一些方法是:


# using approach 1
In [200]: table.flatten(order='F')[:, np.newaxis]
Out[200]: 
array([[11],
       [21],
       [31],
       [41],
       [12],
       [22],
       [32],
       [42],
       [13],
       [23],
       [33],
       [43]])

# using approach 2
In [202]: table.reshape(table.size, order='F')[:, np.newaxis]
Out[202]: 
array([[11],
       [21],
       [31],
       [41],
       [12],
       [22],
       [32],
       [42],
       [13],
       [23],
       [33],
       [43]])