datawhale6月组队学习-task02
1. 数据清洗
1.1 缺失值
# 查看
df.isnull.sum()
# 填充
df.loc[df['Age'].isnull(),'Age'] = df['Age'].mean()
# 删除
1.2 重复值
# 查看重复值
df[df.duplicated()]
# 清理重复值
df = df.drop_duplicates()
1.3 异常值
画箱线图,见task01
2. 特征处理
2.1 分箱处理
# 用cut
#将连续变量Age平均分箱成5个年龄段,并分别用类别变量12345表示
df['AgeBand'] = pd.cut(df['Age'], 5,labels = [1,2,3,4,5])
#将连续变量Age划分为[0,5) [5,15) [15,30) [30,50) [50,80)五个年龄段,并分别用类别变量12345表示
df['AgeBand'] = pd.cut(df['Age'],[0,5,15,30,50,80],labels = [1,2,3,4,5])
#将连续变量Age按10% 30% 50 70% 90%五个年龄段,并用分类变量12345表示
df['AgeBand'] = pd.qcut(df['Age'],[0,0.1,0.3,0.5,0.7,0.9],labels = [1,2,3,4,5])
【参考】https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html
【参考】https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.qcut.html
2.2 文本变量转换
# 查看文本型变量各类别及对应数量
df['Sex'].value_counts()
df['Sex'].unique()
df['Sex'].nunique()
# 将类别编码
# replace、map、使用sklearn.preprocessing的LabelEncoder
df['Sex_num'] = df['Sex'].replace(['male','female'],[1,2])
df['Sex_num'] = df['Sex'].map({'male': 1, 'female': 2})
from sklearn.preprocessing import LabelEncoder
for feat in ['Cabin', 'Ticket']:
lbl = LabelEncoder()
label_dict = dict(zip(df[feat].unique(), range(df[feat].nunique())))
df[feat + "_labelEncode"] = df[feat].map(label_dict)
df[feat + "_labelEncode"] = lbl.fit_transform(df[feat].astype(str))
# one-hot编码
for feat in ["Age", "Embarked"]:
x = pd.get_dummies(df[feat], prefix=feat)
df = pd.concat([df, x], axis=1)
# 从纯文本Name特征里提取出Titles的特征(所谓的Titles就是Mr,Miss,Mrs等)
df['Title'] = df.Name.str.extract('([A-Za-z]+)\.', expand=False)