numpy中有两种方法可以实现一维、二维数组的转置:reshape和T,详细见代码及运行结果如下:一维行向量c调用T生成的结果d仍为一维行向量,并没有完成转置,当c转为二维数组时可以调用T实现转置;reshape在一维、二维的情况下均可完成转置。
import numpy as np
a = np.ones(6)#默认生成行向量
b = 3*a.reshape(6,1)
c = np.array([1,2,3,4])
d = c.T #仅适用于二维数组
print(a)
print(b)
print(c)
print(d)
print(a.shape,b.shape,c.shape,d.shape)
#一维数组的运行结果
'''
[1. 1. 1. 1. 1. 1.]
[[3.]
[3.]
[3.]
[3.]
[3.]
[3.]]
[1 2 3 4]
[1 2 3 4]
(6,) (6, 1) (4,) (4,)
'''
import numpy as np
a1 = np.ones(6).reshape(2,3)#默认生成行向量
b1 = 3*a1.reshape(3,2)
c1 = np.array([[1,2],[3,4]])
d1 = c1.T #仅适用于二维数组
print(a1)
print(b1)
print(c1)
print(d1)
print(a1.shape,b1.shape,c1.shape,d1.shape)
#二维数组的运行结果
[[1. 1. 1.]
[1. 1. 1.]]
[[3. 3.]
[3. 3.]
[3. 3.]]
[[1 2]
[3 4]]
[[1 3]
[2 4]]
(2, 3) (3, 2) (2, 2) (2, 2)