只需要调用torch.tensor(pd.Dataframe.values)
或是torch.tensor(pd.Series.values)
即可
例子
import pandas as pd
import numpy as np
import torch
def get_tensor_from_pd(dataframe_series):
return torch.tensor(data=dataframe_series.values)
if __name__ == '__main__':
df = pd.DataFrame([[1, 2, 0],
[4, 5, 1],
[3, 4, 0], ], columns=['x1', 'x2', 'y'])
tensor_x = get_tensor_from_pd(df.drop(['y'], axis=1)) # dataframe to tensor
tensor_y = get_tensor_from_pd(df['y']) # dataframe to tensor
print(tensor_x)
print(tensor_y)