Fastest way to reshape numpy 1D array to 4D in a specific sequence?

Question:

I want to reshape the flattened channels array of audio to a 4D array(because audio has 4 channels). Reshape example is below:

Input example: [a1,b1,c1,d1,a2,b2,c2,d2,…]

Output 4D array: [[a1,a2,…], [b1,b2,…], [c1,c2,…], [d1,d2,…]]

Each subarray of the 4D array must be one of the channels of audio.
How can I do it in the fastest way?

Asked By: artyom

||

Answers:

>>> data = np.arange(20)
>>> data
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19])

>>> data.reshape((4, -1), order='F')
array([[ 0,  4,  8, 12, 16],
       [ 1,  5,  9, 13, 17],
       [ 2,  6, 10, 14, 18],
       [ 3,  7, 11, 15, 19]])
Answered By: Woodford

Another possibility is to use np.lib.stride_tricks.as_strided:

a = np.array([1, 2, 3, 4, 11, 22, 33, 44, 111, 222, 333, 444], dtype=np.int16)

x = np.lib.stride_tricks.as_strided(
    a, shape=(4, len(a) // 4), strides=(1 * 2, 4 * 2)
)
print(x)

Prints:

[[  1  11 111]
 [  2  22 222]
 [  3  33 333]
 [  4  44 444]]
Answered By: Andrej Kesely