简体   繁体   中英

Reshaping multidimensional array to 2-D array in Python

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

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

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

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

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

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

why you don't just do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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