在Python中重塑多维数组到二维数组。

时间:2022-12-30 21:38:37

I have a 4-D array a where a.shape = (300, 300, 40, 193)

我有一个4-D的数组a。形状= (300,300,40,193)

I want to reshape it to shape (40, 300*300*193).

我想重塑它的形状(40,300 *300*193)。

So, after the reshape, new_a[0,:] should be equivalent to a[:,:,0,:].ravel()

因此,在整形之后,new_a[0,:]应该等于a[:, 0,:].ravel()

What is proper way to use numpy.reshape to do this?

使用numpy的正确方法是什么。重塑呢?

2 个解决方案

#1


1  

One way to do this is to use np.rollaxis. Roll axis number 2 to be in front of axis number 0, then reshape.

一种方法是使用nprollaxis。横轴2号在轴号0前面,然后再整形。

a = np.rollaxis(a, 2, 0)
a = a.reshape((40, 300*300*193))

Here's a smaller version for demonstration:

这里有一个小版本的演示:

>>> a = np.random.randn(30, 30, 40, 19)
>>> b = np.rollaxis(a, 2, 0)
>>> b = b.reshape((40, 30*30*19))
>>> (b[0, :] == a[:, :, 0, :].ravel()).all()
True

#2


-1  

why you don't just do:

为什么你不这样做:

a.reshape([a.shape[2], a.shape[0]*a.shape[1]*a.shape[3]])
a.shape #(40, 17370000)

#1


1  

One way to do this is to use np.rollaxis. Roll axis number 2 to be in front of axis number 0, then reshape.

一种方法是使用nprollaxis。横轴2号在轴号0前面,然后再整形。

a = np.rollaxis(a, 2, 0)
a = a.reshape((40, 300*300*193))

Here's a smaller version for demonstration:

这里有一个小版本的演示:

>>> a = np.random.randn(30, 30, 40, 19)
>>> b = np.rollaxis(a, 2, 0)
>>> b = b.reshape((40, 30*30*19))
>>> (b[0, :] == a[:, :, 0, :].ravel()).all()
True

#2


-1  

why you don't just do:

为什么你不这样做:

a.reshape([a.shape[2], a.shape[0]*a.shape[1]*a.shape[3]])
a.shape #(40, 17370000)