2

I've been stuck on this numpy operation for a while now. I have an np.array of np.shape (x, y, z) that I want to make into an array of np.shape (y, x, z). I am having a hard time understanding the order on which np.reshape is done. For instance, I would like the values to be grouped by their index in the 2nd dim, and not on the first dimension.

For example, with this array of np.shape (3, 2, 9):

[[[-25 -25  15 -26 -26   0 -26 -26   3]
  [ -8  -2   0 -21  -9  39 -14 -11   2]]

 [[-25   2  18 -26 -10  10 -26 -15  14]
  [ -8  -2   0 -21  -9  39 -14 -11   2]]

 [[-25   2  18 -26 -10  14 -26 -15   5]
  [ -8  -2   3 -21  -9  18 -14 -11   3]]]

I would like the output of np.shape (2,3,9) to be:

[[[-25 -25  15 -26 -26   0 -26 -26   3]
  [-25   2  18 -26 -10  10 -26 -15  14]
  [-25   2  18 -26 -10  14 -26 -15   5]]

 [[ -8  -2   0 -21  -9  39 -14 -11   2]
  [ -8  -2   0 -21  -9  39 -14 -11   2]
  [ -8  -2   3 -21  -9  18 -14 -11   3]]]

And not :

[[[-25 -25  15 -26 -26   0 -26 -26   3]
  [ -8  -2   0 -21  -9  39 -14 -11   2]
  [-25   2  18 -26 -10  10 -26 -15  14]]

 [[ -8  -2   0 -21  -9  39 -14 -11   2]
  [-25   2  18 -26 -10  14 -26 -15   5]
  [ -8  -2   3 -21  -9  18 -14 -11   3]]]

I know this is basic numpy but so far every combination of order='F', array.T, etc got me no luck. Appreciate any help!

4
  • Could you provide an example with integers instead of floats? It's very difficult to quickly recognize which floats correspond to which others. Commented Jul 21, 2019 at 23:32
  • Separately, is your goal to exchange the first and second dimensions, rather than reshaping the array? Commented Jul 21, 2019 at 23:33
  • Sure I edited with integers. That's the goal yes. Is there another function than np.reshape to do this kind of operation ? Commented Jul 21, 2019 at 23:39
  • 2
    I think @Akaisteph7's answer below should do it for you Commented Jul 21, 2019 at 23:40

1 Answer 1

2

I think what you are looking for is swapaxes:

np.swapaxes(x,0,1) #x is your array
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot that's it.
For readablity, I'd almost even recommend np.einsum for cases like this, even though you're not doing any summing. np.einsum('ijk->jik', x)
@DanielF I think it's much clearer with np.swapaxes what the goal is here. But it's great to have alternatives!

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.