Search code examples
pythonnumpyreshape

Reshape maintaining N samples in each row


I have already figured it how to do it but I want to check if there is a more efficient method.

What I want is to reshape a vector and keep samples 0 to 7 in the first row, then samples 8 to 15 in the second row, etc.

Here is an example of the output,

array([[   0,    1,    2, ..., 1221, 1222, 1223],
       [   8,    9,   10, ..., 1229, 1230, 1231],
       [  16,   17,   18, ..., 1237, 1238, 1239],
       ...,
       [  40,   41,   42, ..., 1261, 1262, 1263],
       [  48,   49,   50, ..., 1269, 1270, 1271],
       [  56,   57,   58, ..., 1277, 1278, 1279]])

With the input data looking something like,

array([   0,    1,    2, ..., 1277, 1278, 1279])

Is there a more efficient way other than,

data = np.arange(0, 128*10)

# Reshape for S/H
temp = data.reshape(8*8, -1, order='F')
out = np.zeros((8, int(len(data)/8)))
for idx in range(0, 8):
    out[idx] = temp[idx*8: idx*8+8, :].ravel(order = 'F')

Solution

  • Sorry for my first answer I misread the question.

    Here is a solution base on pure numpy transposition and reshaping:

    np.transpose( data.reshape(8, 8, -1, order='F'), (1,2,0)).reshape(8,-1)
    

    Benchmarking against solutions herebelow gives:

    enter image description here