Transpose A Matrix or Tensor

Goal

This post aims to transpose a matrix or tensor in python using following modules:

  • Numpy
  • Pandas
  • Tensorflow
  • Pytorch

Referring to Chris Albon's blog, I only look at his title and wrote my own contents to deepen my understanding about the topic.

Numpy

library

In [18]:
import numpy as np

Create an array

In [19]:
A = np.array([[1, 2, 3], 
             [4, 5, 6], 
             [7, 8, 9]])
A
Out[19]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

Transpose

In [20]:
A.transpose()
Out[20]:
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])
In [21]:
A.T
Out[21]:
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

Pandas

Library

In [24]:
import pandas as pd

Create a matrix

In [25]:
df = pd.DataFrame(data=[[1, 2, 3],
                        [4, 5, 6],
                        [7, 8, 9]])
df
Out[25]:
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9

Transpose a matrix

In [27]:
df.transpose()
Out[27]:
0 1 2
0 1 4 7
1 2 5 8
2 3 6 9
In [6]:
df.T
Out[6]:
0 1 2
0 1 4 7
1 2 5 8
2 3 6 9

Tensorflow

Liberary

In [1]:
import tensorflow as tf

Create a tensor

In [15]:
with tf.Session():
    tc = tf.constant([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])
    print(tc.eval())
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Transpose a tensor

In [14]:
with tf.Session():
    print(tf.transpose(tc).eval())
[[1 4 7]
 [2 5 8]
 [3 6 9]]

PyTorch

Library

In [30]:
import torch 

Create a tensor

In [31]:
t = torch.Tensor([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])
t
Out[31]:
tensor([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]])

Transpose a tensor

In [42]:
t.transpose(dim0=1, dim1=0)
Out[42]:
tensor([[1., 4., 7.],
        [2., 5., 8.],
        [3., 6., 9.]])

Comments

Comments powered by Disqus