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

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.