我有一个具有以下结构的numpy数组:
A = [[(0, 0, 0), (0, 0, 0)],
[(0, 0, 0), (0, 0, 0)],
[(0, 0, 0), (0, 0, 0)],
[(0, 0, 0), (0, 0, 0)]]
A
具有4行、2列和3个通道(在元组中(。简称:A.shape = (4, 2, 3)
现在我需要在不影响通道的情况下交换行和列。输出应该是这样的:
B = [[(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)],
[(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)]]
B
具有2行、4列和3个通道(元组(。简称:B.shape = (2, 4, 3)
我在几个小时内发现的最好的是:numpy.array(A).transpose()
它适用于图像的1个,但其他图像突然有480个通道XD(A
是我现有的简化版本(,只有3行。
那么我该怎么做呢?
许多可能的方法之一是使用swapaxes
方法:
In [15]: A = np.arange(24).reshape(2, 4, 3)
In [16]: A
Out[16]:
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23]]])
In [17]: A.shape
Out[17]: (2, 4, 3)
In [18]: B = A.swapaxes(0, 1)
In [19]: B.shape
Out[19]: (4, 2, 3)
In [20]: B
Out[20]:
array([[[ 0, 1, 2],
[12, 13, 14]],
[[ 3, 4, 5],
[15, 16, 17]],
[[ 6, 7, 8],
[18, 19, 20]],
[[ 9, 10, 11],
[21, 22, 23]]])
np.swapaxes
之外的另一种方法是使用np.transpose
查看转置和交换的文档,并附上的基本示例
A = [[(0, 0, 0), (0, 0, 0)],
[(0, 0, 0), (0, 0, 0)],
[(0, 0, 0), (0, 0, 0)],
[(0, 0, 0), (0, 0, 0)]]
A = np.array(A)
C = np.transpose(A, (1, 0, 2)) # axes1 and axes2 are switching here which changes the shape from (4,2,3) to (2,4,3)
print(C)
输出:
[[[0 0 0]
[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]
[0 0 0]]]