📜  Python| numpy numpy.transpose()

📅  最后修改于: 2022-05-13 01:55:50.972000             🧑  作者: Mango

Python| numpy numpy.transpose()

借助Numpy numpy.transpose() ,我们可以使用 Numpy 的numpy.transpose()方法在一行内执行简单的转置函数。它可以转置二维数组,另一方面它对一维数组没有影响。此方法转置二维 numpy 数组。

示例 #1:
在这个例子中,我们可以看到只用一行来转置一个数组真的很容易。

Python3
# importing python module named numpy
import numpy as np
 
# making a 3x3 array
gfg = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])
 
# before transpose
print(gfg, end ='\n\n')
 
# after transpose
print(gfg.transpose())


Python3
# importing python module named numpy
import numpy as np
 
# making a 3x3 array
gfg = np.array([[1, 2],
                [4, 5],
                [7, 8]])
 
# before transpose
print(gfg, end ='\n\n')
 
# after transpose
print(gfg.transpose(1, 0))


Python3
# importing python module named numpy
import numpy as np
   
# making a 3x3 array
gfg = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])
   
# before transpose
print(gfg, end ='\n\n')
   
# after transpose
print(gfg.T)


输出:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

[[1 4 7]
 [2 5 8]
 [3 6 9]]

示例 #2:
在这个例子中,我们演示了在 numpy.transpose() 中元组的使用。

Python3

# importing python module named numpy
import numpy as np
 
# making a 3x3 array
gfg = np.array([[1, 2],
                [4, 5],
                [7, 8]])
 
# before transpose
print(gfg, end ='\n\n')
 
# after transpose
print(gfg.transpose(1, 0))
输出:
[[1 2]
 [4 5]
 [7 8]]

[[1 4 7]
 [2 5 8]]

方法二:使用  Numpy ndarray.T 对象。

Python3

# importing python module named numpy
import numpy as np
   
# making a 3x3 array
gfg = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])
   
# before transpose
print(gfg, end ='\n\n')
   
# after transpose
print(gfg.T)

输出

[[1 2 3]
 [4 5 6]
 [7 8 9]]

[[1 4 7]
 [2 5 8]
 [3 6 9]]