6

I want to convert X,Y,Z numpy array to (X*Z)*Y numpy array.

Code(Slow):

 def rearrange(data):
        samples,channels,t_insts=data.shape
        append_data=np.empty([0,channels])
        for sample in range(0,samples):
            for t_inst in range(0,t_insts):
                channel_data=data[sample,:,t_inst]
                append_data=np.vstack((append_data,channel_data))
        return append_data.shape

I am looking for a better vectorized approach if possible

Divakar
  • 218,885
  • 19
  • 262
  • 358
Abhishek Bhatia
  • 9,404
  • 26
  • 87
  • 142

1 Answers1

11

You can use np.transpose to swap rows with columns and then reshape -

data.transpose(0,2,1).reshape(-1,data.shape[1])

Or use np.swapaxes to do the swapping of rows and columns and then reshape -

data.swapaxes(1,2).reshape(-1,data.shape[1])
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • Is there some more general method for this? Say I want to convert array of shape `(4,5,6,7,8,9)` to `(4,5*6*8,7,9)` – Gulzar Jun 17 '19 at 14:38
  • @Gulzar `a.transpose(0,1,2,4,3,5)` and then reshape to desired shape. Idea being - Bring the axes to be merged in sequence and then reshape. This could be a relevant post - https://stackoverflow.com/a/47978032/ – Divakar Jun 17 '19 at 14:55