Ravel()3D阵列以一种特殊的顺序--Python

时间:2015-08-06 18:30:20

标签: python numpy multidimensional-array flatten

假设我有以下数组:

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]]])

我在其上使用标准ravel()。这就是我得到的:

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])

相反,我需要以不同的顺序,即:

0 9 18 1 10 19 2 11 20 3 12 21 4 13 22 5 14 23 6 15 24 7 16 25 8 17 26

不幸的是,即使是ravel中的order参数也无济于事,产生:

a.ravel(order='F')

array([ 0,  9, 18,  3, 12, 21,  6, 15, 24,  1, 10, 19,  4, 13, 22,  7, 16,
       25,  2, 11, 20,  5, 14, 23,  8, 17, 26])

这是Fortran订单,这是我找到的最接近我需要的东西,但仍然不是我想要的。 有人知道如何按我需要的顺序获取值吗?

1 个答案:

答案 0 :(得分:3)

>>> a.transpose(1, 2, 0).ravel()
array([ 0,  9, 18,  1, 10, 19,  2, 11, 20,  3, 12, 21,  4, 13, 22,  5, 14,
       23,  6, 15, 24,  7, 16, 25,  8, 17, 26])