我有这个numpy数组:
a = np.array([[[1,2,3],[-1,-2,-3]],[[4,5,6],[-4,-5,-6]]])
b
是a
的转置。我希望b是这样的:
b = np.array([[[1,-1],[2,-2],[3,-3]],[[4,-4],[5,-5],[6,-6]]])
是否可以在一行中完成?
修改
如果我有这个:
a = np.empty(3,dtype = object)
a[0] = np.array([[1,2,3],[-1,-2,-3]])
a[1] = np.array([[4,5,6],[-4,-5,-6]])
我怎样才能得到b?
答案 0 :(得分:4)
您可以使用np.transpose(a,(0,2,1))
执行此操作:
In [26]: a = np.array([[[1,2,3],[-1,-2,-3]],[[4,5,6],[-4,-5,-6]]])
In [27]: b = np.transpose(a,(0,2,1))
In [28]: print a
[[[ 1 2 3]
[-1 -2 -3]]
[[ 4 5 6]
[-4 -5 -6]]]
In [29]: print b
[[[ 1 -1]
[ 2 -2]
[ 3 -3]]
[[ 4 -4]
[ 5 -5]
[ 6 -6]]]
对于编辑dtype=object
数组的编辑问题 - 没有直接计算转置的方法,因为numpy不知道如何转置通用对象。但是,您可以使用列表推导并分别转置每个对象:
In [90]: a = np.empty(2,dtype = object)
In [91]: a[0] = np.array([[1,2,3],[-1,-2,-3]])
In [92]: a[1] = np.array([[4,5,6],[-4,-5,-6]])
In [93]: print a
[[[ 1 2 3]
[-1 -2 -3]] [[ 4 5 6]
[-4 -5 -6]]]
In [94]: b = np.array([np.transpose(o) for o in a],dtype=object)
In [95]: print b
[[[ 1 -1]
[ 2 -2]
[ 3 -3]]
[[ 4 -4]
[ 5 -5]
[ 6 -6]]]