在没有 np.concatenate 或 np.append 的情况下将 3D numpy 数组转换为 2D

Converting a 3D numpy array to 2D without np.concatenate or np.append

x = np.array[[[8, 7, 1, 0, 3],
              [2, 8, 5, 5, 2],
              [1, 1, 1, 1, 1]],

             [[8, 4, 1, 0, 0],
              [6, 8, 5, 5, 2],
              [1, 1, 1, 1, 1]],

             [[2, 4, 0, 2, 3],
              [2, 5, 5, 3, 2],
              [1, 1, 1, 1, 1]],

             [[4, 7, 2, 8, 0],
              [1, 3, 6, 5, 2],
              [1, 1, 1, 1, 1]]]

我有一个这样的 NumPy 数组,我想将它从 3D 转换为 2D,如下所示。

x = np.array[[[8, 7, 1, 0, 3, 8, 4, 1, 0, 0, 2, 4, 0, 2, 3, 4, 7, 2, 8, 0],
              [2, 8, 5, 5, 2, 6, 8, 5, 5, 2, 2, 5, 5, 3, 2, 1, 3, 6, 5, 2],
              [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

实际上我的数组非常大,我在处理这个问题时遇到了问题,但使用相同的逻辑。

我无法使用 np.concatenate 或 np.append,因为它们运行速度太慢。

还有其他方法吗?

实际上我正在使用这个数组与 matplotlib 一起绘图。

plt.imshow(x)
plt.show()

如果有一种方法可以使用 matplotlib 绘制此 3D 数组而不将其转换为 2D,那就太好了。

您可以使用 np.hstack():

print(np.hstack(x))

打印:

[[8 7 1 0 3 8 4 1 0 0 2 4 0 2 3 4 7 2 8 0]
 [2 8 5 5 2 6 8 5 5 2 2 5 5 3 2 1 3 6 5 2]
 [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]]

您可以尝试使用 ndarray.swapaxes + ndarray.reshape

x.swapaxes(0, 1).reshape(x.shape[1], -1)
array([[8, 7, 1, 0, 3, 8, 4, 1, 0, 0, 2, 4, 0, 2, 3, 4, 7, 2, 8, 0],
       [2, 8, 5, 5, 2, 6, 8, 5, 5, 2, 2, 5, 5, 3, 2, 1, 3, 6, 5, 2],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

Timeit 结果:

In [102]: %timeit x.swapaxes(0, 1).reshape(x.shape[1], -1)                      
818 ns ± 21.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [103]: %timeit np.hstack(x)                                                  
6.6 µs ± 42.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

swapaxes + reshape 这里快了近 8 倍。

Online demo in repl.it