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

1 Answer 1

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])
Sign up to request clarification or add additional context in comments.

2 Comments

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 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 - stackoverflow.com/a/47978032

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.