折叠除前两个以​​外的numpy数组的所有维 [英] collapsing all dimensions of numpy array except the first two

查看:97
本文介绍了折叠除前两个以​​外的numpy数组的所有维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个尺寸可变的numpy数组,例如,它可能具有以下形状

I have a variable dimension numpy array, for example it could have the following shapes

(64, 64)
(64, 64, 2, 5)
(64, 64, 40)
(64, 64, 10, 20, 4)

我想做的是,如果维数大于3,我想在保持顺序的同时将其他所有内容折叠/堆叠到第三个维中.因此,在我上面的示例中,操作后的形状应为:

What I want to do is that if the number of dimensions is greater than 3, I want to collapse/stack everything else into the third dimension while preserving order. So, in my above example the shapes after the operation should be:

(64, 64)
(64, 64, 10)
(64, 64, 40)
(64, 64, 800)

此外,还需要保留订单.例如,形状为(64, 64, 2, 5)的数组应堆叠为

Also, the order needs to be preserved. For example, the array of the shape (64, 64, 2, 5) should be stacked as

(64, 64, 2)
(64, 64, 2)
(64, 64, 2)
(64, 64, 2)
(64, 64, 2)

即3D切片一个接一个.另外,在操作之后,我想将其重塑回原始形状而没有任何排列,即保留原始顺序.

i.e. the 3D slices one after the other. Also, after the operation I would like to reshape it back to the original shape without any permutation i.e. preserve the original order.

我可以做的一种方法是将所有尺寸值从3乘以最后一个尺寸,即

One way I could do is multiply all the dimension values from 3 to the last dimension i.e.

shape = array.shape
if len(shape) > 3:
    final_dim = 1
    for i in range(2, len(shape)):
        final_dim *= shape[i]

,然后重新调整数组的形状.像这样:

and then reshape the array. Something like:

array.reshape(64, 64, final_dim)

但是,我首先不确定是否可以按照我的意愿保留订单,以及是否有更好的pythonic方式来实现此目的?

However, I was first of all not sure if the order is preserved as I want and whether there is a better pythonic way to achieve this?

推荐答案

重塑接受自动重尺寸:

a=rand(20,20,8,6,4)
s=a.shape[:2]
if a.ndim>2 : s = s+ (-1,)
b=a.reshape(s)

这篇关于折叠除前两个以​​外的numpy数组的所有维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆