Python:将1D列表转换为3D numpy数组
我有一个列表Python:将1D列表转换为3D numpy数组,python,numpy,Python,Numpy,我有一个列表a,需要将其转换为一个numpy数组b,其形状(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
a
,需要将其转换为一个numpy数组b
,其形状(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)
有没有更短的方法呢?另一种方法是:
import numpy as np
np.reshape(sorted(a), (2, 3, 4))
如果您已经将a
转换为数组,请执行以下操作:
np.reshape(np.sort(a), (2, 3, 4))
另一种方法是:
import numpy as np
np.reshape(sorted(a), (2, 3, 4))
如果您已经将a
转换为数组,请执行以下操作:
np.reshape(np.sort(a), (2, 3, 4))
使用
重塑
和转置
:
a.reshape(-1, 2).T.reshape(-1, 3, 4)
样本阵列上的计时:
%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)
使用
重塑
和转置
:
a.reshape(-1, 2).T.reshape(-1, 3, 4)
样本阵列上的计时:
%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)
您还可以将
a[::2]
和a[1::2]
堆叠起来,然后对其进行重塑。我不知道它是否会短得多。最终,您要做两件事:取消交错和数组,重塑数组和任何可读解决方案将涉及两个步骤,就像您现有的步骤一样。您还可以将a[::2]
和a[1::2]
堆叠起来,然后重塑它。我不知道它是否会短得多。最终,您要做两件事:取消交错和阵列,以及重塑阵列和任何可读解决方案将涉及两个步骤,就像您现有的步骤一样。长阵列效率低下。长阵列效率低下。