Transpose matrix in numpy

I have this numpy array:

a = np.array([[[1,2,3],[-1,-2,-3]],[[4,5,6],[-4,-5,-6]]]) 

b is the transposition of a . I want it to be like this:

 b = np.array([[[1,-1],[2,-2],[3,-3]],[[4,-4],[5,-5],[6,-6]]]) 

Is it possible to do this on one line?


EDIT:

And if I have this:

 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]]) 

How can i get b?

+6
source share
1 answer

You can do this using 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]]] 

For your edited question with an dtype=object array, there is no direct way to calculate transpose, because numpy does not know how to transpose a common object. However, you can use the rethinking of lists and move each object separately:

 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]]] 
+4
source

Source: https://habr.com/ru/post/903101/


All Articles