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)
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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With