简体   繁体   中英

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)

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())

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM