Home > other >  Reshaping each element of a multidimension 3D array to another Multidimension 3D array in Python
Reshaping each element of a multidimension 3D array to another Multidimension 3D array in Python

Time:07-13

I'm working on a problem where I've to reshape a (63,16,3) array's each element to an array (4,4,3), and I'm stuck there.

I generated an array of (63,16,3) using the random function of NumPy. Please help me how to reshape that array's each element into a (4,4,3) and store those outputs into an array.

import numpy as np
a = np.random.rand(63, 16, 3)

return an array b whose each element is (4,4,3)

I have successfully converted the array (63, 16, 3) into (4, 4, 3) but elementwise. What I mean can be cleared using the below snippet of code.

a_resize_0th_element =  a[0].reshape(4,4,3)

But I'm looking for a method where this element-wise operation of transforming a (16, 3) array into the shape of (4, 4, 3) and can be done for all the 63 elements of array a and store everything into array b.

CodePudding user response:

You just need reshape(). The size of the array is 63 * 16 * 3 = 3,024 elements. If you want to divide that into 4x4x3 arrays, that's 3,024 / (4 * 4 * 3) = 63 elements.

So:

b = np.reshape(a, (63, 4, 4, 3))
print(b[0].shape)

Result:

(4, 4, 3)

So, b is an array with 63 shape (4, 4, 3) arrays.

Note: obviously, 4 * 4 = 16 here, but generally this works. However, if you don't want to do the math yourself, you can also just use this:

b = np.reshape(a, (-1, 4, 4, 3))

The -1 will cause numpy to figure it out itself and it will give you the same result.

  • Related