For converting a PyTorch Tensor to a Pandas DataFrame, first, you need to convert the tensor into a numpy array. Then, after getting a numpy array, you can convert it into a Pandas DataFrame.

So, it is a two-step process. However, these steps can vary depending on the current situation. For example, if your tensors are on the GPU, you need to first move to the CPU because the numpy array works on the CPU, not the GPU.
General conversion steps
- If your tensor is on the GPU, move to the CPU using the .cpu() method. Avoid this step if you are already working on the CPU.
- If gradients are required, you need to detach the tensor from the computation graph using the .detach() method.
- Convert the tensor into a numpy array using the .numpy() method.
- Convert that numpy array into a DataFrame using pd.DataFrame() method.
Install the Pandas and PyTorch libraries if you haven’t already.
Converting a 1D tensor into a DataFrame
import torch import pandas as pd tensor_1d = torch.tensor([48, 6, 19, 21]) print(tensor_1d) # Output: tensor([48, 6, 19, 21]) print(type(tensor_1d)) # Output: <class 'torch.Tensor'> # Converting to a data frame df = pd.DataFrame( tensor_1d.cpu().numpy(), # Ensures CPU and converts to NumPy columns=['Values'] # Explicitly name the column ) print(df) # Output: # Values # 0 48 # 1 6 # 2 19 # 3 21 print(type(df)) # Output: <class 'pandas.core.frame.DataFrame'>
And we have a data frame with one column. You can also pass your index if you want custom row labels.
Converting 2D Tensor to Tabular DataFrame
import torch import pandas as pd tensor = torch.arange(6).reshape(2, 3) df2 = pd.DataFrame( tensor.numpy(), index=["row1", "row2"], columns=["col1", "col2", "col3"] ) print(df2) # Output: # col1 col2 col3 # row1 0 1 2 # row2 3 4 5
Combining multiple tensors
Let’s combine multiple 1D vectors and create a DataFrame out of them.import torch import pandas as pd a = torch.tensor([1, 2, 3]) b = torch.tensor([4, 5, 6]) df_combo = pd.concat( [pd.Series(a.numpy(), name="A"), pd.Series(b.numpy(), name="B")], axis=1 ) print(df_combo) # Output: # A B # 0 1 4 # 1 2 5 # 2 3 6That’s all!