如何在Python中进行2D数组的转置,而不使用内置的transpose()函数?
但是,这给了我一个错误:-索引2超出了轴0的范围,大小为2我保持代码基本相同:如何在Python中进行2D数组的转置,而不使用内置的transpose()函数?,python,arrays,numpy,transpose,Python,Arrays,Numpy,Transpose,但是,这给了我一个错误:-索引2超出了轴0的范围,大小为2我保持代码基本相同: 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(le
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]
输出:
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)
使用函数还有其他numpy技巧,但我假设您希望使用for循环。
a,b=a5。shape
比使用len更直接。如果在范围表达式中使用这些变量,则更容易获得正确的索引顺序。
[[1. 4.]
[2. 5.]
[3. 6.]]