How to create new pandas dataframe column containing values of all other columns as a tensor?
I'm trying to create a new feature column which is a tensor containing the values in the existing columns. So if col A's value is '1', col B's value is '0', and col C's value is 0, then the new feature column's value will be [1,0,0].
I tried the following code:
import numpy as np
import pandas as pd
import torch

df = pd.DataFrame({&quot;A&quot;:[1,1,0], &quot;B&quot;:[0,1,1], &quot;Sentiment&quot;:[0,0,1]})

df[&quot;new_feature&quot;] = [df[&quot;A&quot;].values, df[&quot;B&quot;].values, df[&quot;C&quot;].values]



...but the result is not what I need. The result is getting the values down each column rather than the values across the row (multiple column values). For example, the new_feature column value for the first row should be [1,0,0] but its showing [1,1,0]
My ultimate aim is to get a dataframe column that I can use as a torch tensor to input into a neural net.

Use torch.from_numpy with apply lambda function.

df["new_feature"] = df.apply(lambda x:torch.from_numpy(x.to_numpy()), axis = 1)
df
   A  B  C                        new_feature
0  1  0  0  [tensor(1), tensor(0), tensor(0)]
1  1  1  0  [tensor(1), tensor(1), tensor(0)]
2  0  1  1  [tensor(0), tensor(1), tensor(1)]

df["new_feature"][0]
tensor([1, 0, 0])



First convert dataframe values to numpy array using pd.Series.to_numpy and
then convert numpy array to tensor using torch.from_numpy.
