Numpy 数组 - 使用重塑将数组末尾的多列堆叠为行

Numpy array - stack multiple columns at the end of an array as rows using reshape

我想在数组末尾堆叠 n 列作为新行。我试图通过重塑来做到这一点,但我做不到。例如给定 table

table = np.array([[11,12,13,14,15,16],
                  [21,22,23,24,25,26],
                  [31,32,33,34,35,36],
                  [41,42,43,44,45,46]])

如果 n=2 我的输出应该是:

array([[11, 12], 
       [21, 22], 
       [31, 32], 
       [41, 42], 
       [13, 14], 
       [23, 24], 
       [33, 34], 
       [43, 44], 
       [15, 16], 
       [25, 26], 
       [35, 36], 
       [45, 46]])

如果n=3:

array([[11, 12, 13], 
       [21, 22, 23], 
       [31, 32, 33], 
       [41, 42, 43], 
       [14, 15, 16], 
       [24, 25. 26], 
       [34, 35, 36], 
       [44, 45, 46]])

更新:

好的,我通过以下命令成功实现了我想要的结果:

import numpy as np

n=2
np.concatenate(np.split(table, table.shape[1]/n, axis=1), axis=0)
n=3
np.concatenate(np.split(table, table.shape[1]/n, axis=1), axis=0)

我不知道是否可以通过整形完成。

OP 提供了一个解决方案:

np.concatenate(np.split(table, table.shape[1]/n, axis=1), axis=0)

它似乎效率低下,因为 np.split 强制将数据更改为数组列表,然后在外部参数中对其进行迭代。超过 np.concatenate 也不是那么有效。当列表项的长度不平衡时,它们是工作的理想选择。

我的解决方案是这样的:

np.vstack(table.reshape(4,3,2).swapaxes(0,1))
#np.vstack(table.reshape(4,2,3).swapaxes(0,1)) #for second case

让我们检查一下我对性能的预测是否正确:

%timeit np.vstack(table.reshape(4,3,2).swapaxes(0,1))
%timeit np.concatenate(np.split(table, table.shape[1]/2, axis=1), axis=0)

输出:

22.4 µs ± 2.72 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
42.8 µs ± 9.09 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

我在 numpyviz 的帮助下寻找解决方案(免责声明:我是它的作者)。有一个 numpyviz化有助于更好地理解过程:

一般来说,您需要设置一个形状,以便块保持宽度和高度。 Numpyviz化暗示新形状的 axis=0axis=2 分别对应于 table.shape[0]n。中轴的长度也是table.shape[1]\n的块数。所以你可以像这样传递参数:

table.reshape(table.shape[0], table.shape[1]\n, n)

或者更简单的方式:

table.reshape(table.shape[0], -1, n)