Python| numpy numpy.transpose()
借助Numpy numpy.transpose() ,我们可以使用 Numpy 的numpy.transpose()方法在一行内执行简单的转置函数。它可以转置二维数组,另一方面它对一维数组没有影响。此方法转置二维 numpy 数组。
Parameters:
axes : [None, tuple of ints, or n ints] If anyone wants to pass the parameter then you can but it’s not all required. But if you want than remember only pass (0, 1) or (1, 0). Like we have array of shape (2, 3) to change it (3, 2) you should pass (1, 0) where 1 as 3 and 0 as 2.
Returns: ndarray
示例 #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]]