Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose of a 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 a transpose of a. I want b be like this:

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

Is it possible to do it in one line?


EDIT:

And if I have this instead:

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?

like image 807
Academia Avatar asked Dec 05 '11 11:12

Academia


1 Answers

You can do it 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 array of dtype=object -- there is no direct way to compute the transpose, because numpy doesn't know how to transpose a generic object. However, you can use list comprehension and transpose 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]]]
like image 73
talonmies Avatar answered Sep 22 '22 07:09

talonmies