“反向”转置/展平

2024-05-18 21:23:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个array data形状(3, 3, k),其中长度k是固定的。 阵列被处理成一个扁平的一维阵列:

mat2 = numpy.transpose(data, (1, 0, 2)).flatten('C')

如何反转这个转置/展平过程以获得(3, 3, k)的原始形状和data array的顺序?你知道吗


Tags: numpydata顺序过程array形状transpose扁平
1条回答
网友
1楼 · 发布于 2024-05-18 21:23:59
>>> k = 10
# Generating a `(3, 3, k)` matrix:
>>> a = np.linspace(0, 89, 90).reshape((3, 3, k))
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., 48., 49.],
        [50., 51., 52., 53., 54., 55., 56., 57., 58., 59.]],

       [[60., 61., 62., 63., 64., 65., 66., 67., 68., 69.],
        [70., 71., 72., 73., 74., 75., 76., 77., 78., 79.],
        [80., 81., 82., 83., 84., 85., 86., 87., 88., 89.]]])

# Doing your transform on it:
>>> b = np.transpose(a, (1, 0, 2)).flatten('C')
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 30., 31., 32.,
       33., 34., 35., 36., 37., 38., 39., 60., 61., 62., 63., 64., 65.,
       66., 67., 68., 69., 10., 11., 12., 13., 14., 15., 16., 17., 18.,
       19., 40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 70., 71.,
       72., 73., 74., 75., 76., 77., 78., 79., 20., 21., 22., 23., 24.,
       25., 26., 27., 28., 29., 50., 51., 52., 53., 54., 55., 56., 57.,
       58., 59., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89.])

# Reversing the transform:
>>> c = b.reshape((3, 3, k)).transpose((1, 0, 2))
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., 48., 49.],
        [50., 51., 52., 53., 54., 55., 56., 57., 58., 59.]],

       [[60., 61., 62., 63., 64., 65., 66., 67., 68., 69.],
        [70., 71., 72., 73., 74., 75., 76., 77., 78., 79.],
        [80., 81., 82., 83., 84., 85., 86., 87., 88., 89.]]])

# Figuring out if we did it right:
>>> np.array_equal(a, c)
True

相关问题 更多 >

    热门问题