Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert torch tensor to pandas dataframe?

I'd like to convert a torch tensor to pandas dataframe but by using pd.DataFrame I'm getting a dataframe filled with tensors instead of numeric values.

import torch
import pandas as  pd
x = torch.rand(4,4)
px = pd.DataFrame(x)

Here's what I get when clicking on px in the variable explorer:

0   1   2   3
tensor(0.3880)  tensor(0.4598)  tensor(0.4239)  tensor(0.7376)
tensor(0.4174)  tensor(0.9581)  tensor(0.0987)  tensor(0.6359)
tensor(0.6199)  tensor(0.8235)  tensor(0.9947)  tensor(0.9679)
tensor(0.7164)  tensor(0.9270)  tensor(0.7853)  tensor(0.6921)
like image 927
Niv Avatar asked Sep 15 '19 08:09

Niv


People also ask

Does PyTorch work with pandas?

PyTorch provides many tools to make data loading easy and make your code more readable. In this tutorial, we will see how to load and preprocess Pandas DataFrame.

Does pandas work with Tensorflow?

If your data has a uniform datatype, or dtype , it's possible to use a pandas DataFrame anywhere you could use a NumPy array. This works because the pandas. DataFrame class supports the __array__ protocol, and TensorFlow's tf.

How do you make a torch tensor?

To create a tensor with pre-existing data, use torch.tensor() . To create a tensor with specific size, use torch.* tensor creation ops (see Creation Ops). To create a tensor with the same size (and similar types) as another tensor, use torch.*_like tensor creation ops (see Creation Ops).


2 Answers

I found one possible way by converting torch first to numpy:

import torch
import pandas as  pd

x = torch.rand(4,4)
px = pd.DataFrame(x.numpy())
like image 94
Niv Avatar answered Oct 24 '22 09:10

Niv


You can change type using astype

px = pd.DataFrame(x).astype("float")
px
          0         1         2         3
0  0.847408  0.714524  0.286006  0.165475
1  0.136359  0.384073  0.398055  0.437550
2  0.843704  0.301536  0.576983  0.231726
3  0.293576  0.075563  0.811282  0.881705
like image 24
Dishin H Goyani Avatar answered Oct 24 '22 10:10

Dishin H Goyani