Question

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?

Was it helpful?

Solution

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]]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top