0
import numpy as np

a5 = np.array([[1, 2, 3],[4, 5, 6]])
a = len(a5)              # rows of a5
b = len(a5[0])           # columns of a5
    
a6 = np.zeros([b, a])

for i in range(len(a5)):
    for j in range(len(a5[0])):
        a6[i][j] = a5[j][i]

But, this is giving me Error :- index 2 is out of bounds for axis 0 with size 2

1
  • a, b = a5.shape is more direct than your use of len. If you use those variables in the range expressions it should be easier to get the index order right. Commented Mar 3, 2021 at 7:09

1 Answer 1

1

I kept the code mostly the same:

import numpy as np

a5 = np.array([[1,2,3],[4,5,6]])
a5_transposed = np.zeros((3,2))

for i in range(len(a5)):
    for j in range(len(a5[0])):
        a5_transposed[j,i]=a5[i,j]

print(a5_transposed)

output:

[[1. 4.]
 [2. 5.]
 [3. 6.]]

There are other numpy tricks to do it with a function but I assume that you want to do it with for loops.

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

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.