How to Convert a Pandas DataFrame to a PyTorch Tensor

Here are the steps to convert Pandas DataFrame to PyTorch Tensor in Python:

Step 1: Import Pandas and PyTorch libraries

import pandas as pd
import torch

Step 2: Create a DataFrame that you need to convert

df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]})

Step 3: Convert the Pandas DataFrame to a NumPy array

numpy_array = df.values

Step 4: Convert the NumPy array to a PyTorch tensor

tensor = torch.tensor(numpy_array)

Step 5: Print the PyTorch tensor

print(tensor)

Let’s write the complete code that converts Pandas DataFrame to PyTorch Tensor.

import pandas as pd
import torch

df = pd.DataFrame({'col1': [1, 2, 3],
                   'col2': [4, 5, 6],
                   'col3': [7, 8, 9]})

# Convert the Pandas DataFrame to a NumPy array
numpy_array = df.values

# Convert the NumPy array to a PyTorch tensor
tensor = torch.tensor(numpy_array)

# Print the PyTorch tensor
print(tensor)

Output

tensor([[1, 4, 7],
        [2, 5, 8],
        [3, 6, 9]])

Conclusion

To convert Pandas DataFrame to a PyTorch Tensor, you need to convert DataFrame to a Numpy array using “df.values” and then convert a numpy array to tensor using the “torch.tensor()” method.

Related posts

Convert a 1D IntTensor to int in PyTorch

Python List to PyTorch Tensor

PyTorch Tensor to Python List

Leave a Comment