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]:
Transpose¶
In [20]:
A.transpose()
Out[20]:
In [21]:
A.T
Out[21]:
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]:
Transpose a matrix¶
In [27]:
df.transpose()
Out[27]:
In [6]:
df.T
Out[6]:
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())
Transpose a tensor¶
In [14]:
with tf.Session():
print(tf.transpose(tc).eval())
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]:
Transpose a tensor¶
In [42]:
t.transpose(dim0=1, dim1=0)
Out[42]:
Comments
Comments powered by Disqus