The generic matrix is ​​transposed into numpy

Let a be a list in python.

 a = [1,2,3] 

When the transpose of the matrix is ​​applied to a , we get:

 np.matrix(a).transpose() matrix([[1], [2], [3]]) 

I want to generalize this functionality and will further illustrate what I want to do with an example. Let b be another list.

 b = [[1, 2], [2, 3], [3, 4]] 

In a list items: 1, 2, and 3. I would like to consider each of [1,2] , [2,3] and [3,4] as list items in b , just for the purpose of doing this transpose. I would like the result to be as follows:

 array([[[1,2]], [[2,3]], [[3,4]]]) 

In general, I would like to be able to specify what the list item will look like and perform matrix transformation based on this.

I could just write a few lines of code to do this, but my goal is to ask this question to find out if there is a built-in numpy function or a pythonic way to do this.

EDIT: the output of unutbu below corresponds to the output that I have above. However, I wanted to find a solution that would work in a more general case. I posted another input / output below. My initial example was not descriptive enough to convey what I wanted to say. Let the elements in b be [1,2] , [2,3] , [3,4] and [5,6] . Then the result below will transpose the matrix on the elements of higher dimension. More generally, as soon as I describe how the “element” will look, I would like to know if there is a way to do something like transpose.

 Input: b = [[[1, 2], [2, 3]], [[3, 4], [5,6]]] Output: array([[[1,2], [3,4]], [[2,3], [5,6]]]) 
+6
source share
1 answer

Your desired array has the form (3,1,2). b has the form (3.2). To insert an additional axis in the middle, use b[:,None,:] or (equivalently) b[:, np.newaxis, :] . Find "newaxis" in the section under "Main sections" .

 In [178]: b = np.array([[1, 2], [2, 3], [3, 4]]) In [179]: b Out[179]: array([[1, 2], [2, 3], [3, 4]]) In [202]: b[:,None,:] Out[202]: array([[[1, 2]], [[2, 3]], [[3, 4]]]) 

Another handy tool is np.swapaxes :

 In [222]: b = np.array([[[1, 2], [2, 3]], [[3, 4], [5,6]]]) In [223]: b.swapaxes(0,1) Out[223]: array([[[1, 2], [3, 4]], [[2, 3], [5, 6]]]) 

Transpose, bT same as replacing the first and last axes, b.swapaxes(0,-1) :

 In [226]: bT Out[226]: array([[[1, 3], [2, 5]], [[2, 4], [3, 6]]]) In [227]: b.swapaxes(0,-1) Out[227]: array([[[1, 3], [2, 5]], [[2, 4], [3, 6]]]) 

Summary:

  • Use np.newaxis (or None ) to add new axes. (Thus, increasing the dimension of the array)
  • Use np.swapaxes to replace any two axes.
  • Use np.transpose to transfer all axes at once. (Thanks to @jorgeca for pointing this out.)
  • Use np.rollaxis to "rotate" the axes.
+4
source

All Articles