处理分类变量

Python 中的机器学习特征工程

Robert O'Callaghan

Director of Data Science, Ordergroove

编码分类特征

Python 中的机器学习特征工程

编码分类特征

Python 中的机器学习特征工程

编码分类特征

  • One-hot 编码
  • 哑变量编码
Python 中的机器学习特征工程

One-hot 编码

pd.get_dummies(df, columns=['Country'], 
               prefix='C')
    C_France    C_India    C_UK    C_USA
0          0          1       0        0
1          0          0       0        1
2          0          0       1        0
3          0          0       1        0
4          1          0       0        0
Python 中的机器学习特征工程

哑变量编码

pd.get_dummies(df, columns=['Country'],
               drop_first=True, prefix='C')
     C_India    C_UK    C_USA
0          1       0        0
1          0       0        1
2          0       1        0
3          0       1        0
4          0       0        0
Python 中的机器学习特征工程

One-hot 与哑变量

  • One-hot 编码:特征易于解释
  • 哑变量编码:去重后保留必要信息
Python 中的机器学习特征工程
Index Sex
0 Male
1 Female
2 Male
Index Male Female
0 1 0
1 0 1
2 1 0
Index Male
0 1
1 0
2 1
Python 中的机器学习特征工程

限制列数量

counts = df['Country'].value_counts()
print(counts)
'USA'      8
'UK'       6
'India'    2
'France'   1
Name: Country, dtype: object
Python 中的机器学习特征工程

限制列数量

mask = df['Country'].isin(counts[counts < 5].index)

df['Country'][mask] = 'Other'
print(pd.value_counts(colors))
'USA'      8
'UK'       6
'Other'    3
Name: Country, dtype: object
Python 中的机器学习特征工程

现在您会处理分类变量了

Python 中的机器学习特征工程

Preparing Video For Download...