Queenish01
Queenish01

Reputation: 51

How to do transpose of a 2D array in Python, without using the built-in transpose() function?

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

Upvotes: 0

Views: 1160

Answers (1)

joostblack
joostblack

Reputation: 2525

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.

Upvotes: 1

Related Questions