3

I have a 12X2 array I want to reorganize into a 3x4x2 array. Specifically, I want to change

a = np.array(([1,13],[2,14],[3,15],[4,16],[5,17],[6,18],[7,19],[8,20],[9,21],[10,22],[11,23],[12,24]))

 [[ 1 13]
[ 2 14]
[ 3 15]
[ 4 16]
[ 5 17]
[ 6 18]
[ 7 19]
[ 8 20]
[ 9 21]
[10 22]
[11 23]
[12 24]]`

Into a matrix that looks like this:

[[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]]
[[ 13. 14. 15. 16.]
[ 17. 18. 19. 20.]
[ 21. 22. 23. 24.]]]

I was thinking a triple-nested for loop, but the way I coded it is not going to work. And I can't wrap my head around numpy indexing enough to figure out how to do this.

This is of course example code. I want to alter this for use to make 3 plots of the leading 3 EOFs of global precipitation on a latitude-longitude grid. The EOFs are being pulled from a 8192x8192 array and put into a 64x128x3 array. (I'm only using the first 3 columns of the large matrix. Each column is an EOF, and down each one, values are listed by longitude going along the first latitude, then listed by longitude again going along the second latitude, and so on down until the 128th latitude at the bottom of the column. Of course my array will be upside-down with respect to the base map when I finish since the first latitude is -87.something, but I plan to use np.flipud to fix it once it's finished.

2 Answers 2

2

You can use a combination of np.reshape and np.transpose, like so -

a.reshape(3,4,-1).transpose(2,0,1)

So, for your actual case (if I understood it correctly) would be -

a.reshape(64,128,-1).transpose(2,0,1)

Please note that the output shape in this case would be (3, 64, 128) though. So, I am assuming the sample case doesn't properly correspond to your actual case.

Sign up to request clarification or add additional context in comments.

3 Comments

That just gave me back the exact same matrix. My matrix now is (2,0,1) and I want to change it to (3,4,2)
@ChristineB The expected output listed in the question looks like has shape (2,3,4) (2 along axis=0, 3 along axis=1 which are rows, 4 along axis=2 which are columns). Are you sure you want a shape of (3,4,2)? Would a.reshape(3,4,2) work for you?
Nevermind my comment. I typed what you suggested & print(a) on the next line, but I forgot to replace variable a with its reshape+transpose. Thanks!
1

There are many ways to do it, how about a.T.reshape(2,3,4):

n [14]: a.T.reshape(2,3,4)
Out[14]: 
array([[[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]],

       [[13, 14, 15, 16],
        [17, 18, 19, 20],
        [21, 22, 23, 24]]])

Comments

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.