Numpy数组 - 使用reshape将多个列堆叠成一个

问题描述 投票:1回答:2

对于像这样的2D数组:

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

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

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

重塑可以将所有行组合成一行,我想知道它是否可以组合列以使代码更清晰,可能更快。

single_row = table.reshape(-1)
python arrays numpy reshape numpy-ndarray
2个回答
1
投票

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

table.T.reshape(-1, 1)

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

1
投票

还有一些方法是:


# 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]])
© www.soinside.com 2019 - 2024. All rights reserved.