Python:将1D列表转换为3D numpy数组

时间:2018-09-07 19:55:49

标签: python numpy

我有一个列表${ANT_HOME}/lib/ant.jar,需要将其转换为形状为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]]])

有没有更短的方法?

2 个答案:

答案 0 :(得分: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.]]])

答案 1 :(得分:0)

另一种方式是:

import numpy as np
np.reshape(sorted(a), (2, 3, 4))

如果您已经将a转换为数组,请执行以下操作:

np.reshape(np.sort(a), (2, 3, 4))
相关问题