简体   繁体   English

如何重塑 3d numpy 表?

[英]How to reshape 3d numpy table?

I have a 3d numpy table with shape=(2,3,4) like below:我有一个 shape=(2,3,4) 的 3d numpy 表,如下所示:

a = np.array([[[1., 2., 3., 4.],
        [1., 2., 3., 4.],
        [1., 2., 3., 4.]],

       [[5., 6., 7., 8.],
        [5., 6., 7., 8.],
        [5., 6., 7., 8.]]])

And want to reshape this in a way where the columns in each dimension are stacked into a new column in a 2d matrix.并希望以一种将每个维度中的列堆叠成二维矩阵中的新列的方式对其进行重塑。

1  5
1  5
1  5
2  6
2  6
2  6
3  7
3  7
3  7
4  8
4  8
4  8

Here you go:干得好:

res = a.T.reshape((-1,2))

Output:输出:

array([[1., 5.],
       [1., 5.],
       [1., 5.],
       [2., 6.],
       [2., 6.],
       [2., 6.],
       [3., 7.],
       [3., 7.],
       [3., 7.],
       [4., 8.],
       [4., 8.],
       [4., 8.]])

To reshape a numpy array, use the reshape method.要重塑numpy数组,请使用reshape方法。

Basically it looks at the array as it was flattened and works over it with the new given shape.基本上,它在数组被展平时查看它,并使用新的给定形状对其进行处理。 It does however iterates over the last index first, ie, the inner-most list will be processed, then the next and so on.然而,它首先遍历最后一个索引,即最里面的列表将被处理,然后是下一个,依此类推。

So both a np.array([1, 2, 3, 4, 5, 6]).reshape((3, 2)) and a np.array([[1, 2, 3], [4, 5, 6]]).reshape((3, 2)) will give [[1, 2], [3, 4], [5, 6]] , since these two originating arrays are the same when flattened.所以np.array([1, 2, 3, 4, 5, 6]).reshape((3, 2))np.array([[1, 2, 3], [4, 5, 6]]).reshape((3, 2))将给出[[1, 2], [3, 4], [5, 6]] ,因为这两个原始数组在展平时是相同的。

You want a (12, 2) array, or if you read the reshape docs, you can pass (-1, 2) and numpy will figure the other dimension.您需要一个 (12, 2) 数组,或者如果您阅读了reshape文档,您可以传递 (-1, 2) 并且numpy将计算另一个维度。

So if you just give the new shape for your array as is, it will start working with the first list x[0, 0] = [1, 2, 3, 4] , which would become [[1, 2], [3, 4]] , ... That's not what you want.因此,如果您按原样为数组提供新形状,它将开始使用第一个列表x[0, 0] = [1, 2, 3, 4] ,它将变为[[1, 2], [3, 4]] , ... 这不是你想要的。

But note that if you transpose your array first, then you'll have the items you want in the inner lists (fast varying index):但请注意,如果您先转置数组,则内部列表中将包含所需的项目(快速变化的索引):

In : x.T
Out: 
array([[[1., 5.],
        [1., 5.],
        [1., 5.]],

       [[2., 6.],
        [2., 6.],
        [2., 6.]],

       [[3., 7.],
        [3., 7.],
        [3., 7.]],

       [[4., 8.],
        [4., 8.],
        [4., 8.]]])

Which is almost what you want, except for the extra dimension.这几乎是你想要的,除了额外的维度。 So now you can just reshape this and get your (12, 2) array the way you want:所以现在你可以重塑它并按照你想要的方式获得你的 (12, 2) 数组:

In : x.T.reshape((-1, 2))
Out: 
array([[1., 5.],
       [1., 5.],
       [1., 5.],
       [2., 6.],
       [2., 6.],
       [2., 6.],
       [3., 7.],
       [3., 7.],
       [3., 7.],
       [4., 8.],
       [4., 8.],
       [4., 8.]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM