Numpy数组使用整形将多个列堆叠到一个列中

2024-06-26 18:11:25 发布

您现在位置:Python中文网/ 问答频道 /正文

对于这样的二维阵列:

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

是否可以在table上使用np.reshape来获得一个数组single_column,其中{}的每一列都是垂直堆叠的?这可以通过拆分table并与vstack结合来实现。在

single_column = np.vstack(np.hsplit(table , table .shape[1]))

整形可以将所有行合并为一行,我想知道它是否也可以合并列,以使代码更干净,可能更快。在

^{pr2}$

Tags: 代码nptablecolumn数组arrayshapesingle
2条回答

您可以先转置,然后重塑:

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

相关问题 更多 >