python - 如何将 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))
有效,但我不确定是否有更好的方法。
解决方案
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)
推荐阅读
- php - 在并发 VHost 的情况下,哪一个正在服务?
- spring - Spring Boot @Async 等待所有线程完成
- php - 使用 PHP 发送 POST 请求
- liferay - 在 Liferay 主题中,“clay/base”和“clay/atlas”有什么区别
- css - 使用 ::before 伪显示 flex 在 Safari 上不起作用
- javascript - 如何根据用户在下拉列表中的选择显示特定的 HTML 元素
- python - 如果没有及时验证,Django自动删除用户
- python - Conda - 将 python3 版本更改为 3.6.8
- java - 在类类型中使用变量
- appium - Appium Inspector 未启动会话(--allow cors 错误)