python - Python:将 1D 列表转换为 3D numpy 数组
问题描述
我有一个列表a
,需要按以下顺序将其转换为b
具有形状和元素的 numpy 数组。(2, 3, 4)
a = [0, 12, 1, 13, 2, 14, 3, 15, 4, 16, 5, 17, 6, 18, 7, 19, 8, 20, 9, 21, 10, 22, 11, 23]
b = array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
我尝试了一下,得到了这两种方法:
b = np.rollaxis(np.asarray(a).reshape(3, 4, 2), 2)
b = np.asarray(a).reshape(2,4,3, order="F").swapaxes(1, 2)
有没有更短的方法来做到这一点?
解决方案
使用reshape
和transpose
:
a.reshape(-1, 2).T.reshape(-1, 3, 4)
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
您的样本阵列上的计时:
%timeit np.rollaxis(a.reshape(3, 4, 2), 2)
2.92 µs ± 10.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit a.reshape(2,4,3, order="F").swapaxes(1, 2)
1.1 µs ± 11.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit a.reshape(-1, 2).T.reshape(-1, 3, 4)
1.08 µs ± 7.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
我没有在大规模数组上计时这个答案,因为我还没有找到一种方法来概括你的任何一个解决方案。我的解决方案的一个好处是它可以在不更改任何代码的情况下进行扩展:
a = np.zeros(48)
a[::2] = np.arange(24)
a[1::2] = np.arange(24, 48)
a.reshape(-1, 2).T.reshape(-1, 3, 4)
array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]],
[[12., 13., 14., 15.],
[16., 17., 18., 19.],
[20., 21., 22., 23.]],
[[24., 25., 26., 27.],
[28., 29., 30., 31.],
[32., 33., 34., 35.]],
[[36., 37., 38., 39.],
[40., 41., 42., 43.],
[44., 45., 46., 47.]]])
推荐阅读
- racket - 如何在 Racket REPL 中设置元语言?
- node.js - 如何解决 npm install 在 Windows 上抛出 fsevents 警告?
- amazon-web-services - AWS:通过 RDS 快照创建事件发布 SNS 消息的问题
- python - 根据项的功能条件重新排列字典
- python-requests - FastAPI 文件上传
- java - Apache Ignite 异步方法实际上是如何工作的?
- flutter - 颤动中的自动刷新网页视图
- environment-variables - Next.js:如何为不同的环境使用不同的 env 文件?
- python - Received ValueError: I/O operation on closed file but the data print well
- groovy - 如何在 ReadyAPI 的循环中使用不同的数据发出请求,并且响应应该在另一个文件中生成?