首页 > 解决方案 > 如何将 numpy 数组从 (2,4) 转换为 (4, 2)

问题描述

如何将数组转换a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])b = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]).

所以输入将是:

array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

和输出:

array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])

注意 -a.flatten().reshape((4, 2))有效,但我不确定是否有更好的方法。

标签: pythonnumpy

解决方案


flatten正如其他人已经指出的那样,您不需要numpy 数组。一个更强大的解决方案是reshape通过翻转shape值。这样,您不必担心指定(4,2)

a = a.reshape(a.shape[1],a.shape[0])
print(a)

输出:

array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])

10000x20000 numpy 数组的运行时测试

>>> a = np.random.random((10000,20000))
>>> %timeit -n 100000 a.reshape(a.shape[1],a.shape[0])
601 ns ± 12.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit -n 100000 a.reshape(-1, a.shape[0])
520 ns ± 18.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

推荐阅读