pandas.get_dummies 的用法
get_dummies 是利用pandas实现one hot encode的方式。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.utils.data import Dataset,DataLoader,TensorDataset
dftrain_raw = pd.read_csv('/content/eat_pytorch_in_20_days/data/titanic/train.csv')
dftest_raw = pd.read_csv('/content/eat_pytorch_in_20_days/data/titanic/test.csv')
dftrain_raw.head(10)
Pclass:乘客所持票类,有三种值(1,2,3) 【转换成onehot编码】
dfdata = dftrain_raw
dfresult= pd.DataFrame()
#Pclass
dfPclass = pd.get_dummies(dfdata['Pclass'])
get_dummies 后:
dfPclass.columns = ['Pclass_' +str(x) for x in dfPclass.columns ]
dfresult = pd.concat([dfresult,dfPclass],axis = 1)
dfresult
Embarked:乘客登船港口:S、C、Q(有缺失)【转换成onehot编码,四维度 S,C,Q,nan】
pd.get_dummies(dfdata['Embarked'],dummy_na=True)
dfEmbarked = pd.get_dummies(dfdata['Embarked'],dummy_na=True)
dfEmbarked.columns = ['Embarked_' + str(x) for x in dfEmbarked.columns]
dfresult = pd.concat([dfresult,dfEmbarked],axis = 1)