python中get_dummies实践

原文链接 https://blog.csdn.net/dongyanwen6036/article/details/78555163

一、实践     
离散特征的编码分为两种情况:

1、离散特征的取值之间没有大小的意义,比如color:[red,blue],那么就使用one-hot编码
2、离散特征的取值有大小的意义,比如size:[X,XL,XXL],那么就使用数值的映射{X:1,XL:2,XXL:3}说明:对于有大小意义的离散特征,直接使用映射就可以了,{'XL':3,'L':2,'M':1}
使用pandas可以很方便的对离散型特征进行one-hot编码

#-*-coding=utf-8-*-
import pandas as pd  
df = pd.DataFrame([  
            ['green', 'M', 10.1, 'class1'],   
            ['red', 'L', 13.5, 'class2'],   
            ['blue', 'XL', 15.3, 'class1']])  
  
df.columns = ['color', 'size', 'prize', 'class label']  
  
size_mapping = {  
           'XL': 3,  
           'L': 2,  
           'M': 1}  
df['size'] = df['size'].map(size_mapping)  
  
class_mapping = {label:idx for idx,label in enumerate(set(df['class label']))}  
df['class label'] = df['class label'].map(class_mapping)
print('----------------------------------------------------------------')
 
print(df)
 
print('----------------------------------------------------------------')
df=pd.get_dummies(df)  
print(df)
print('----------------------------------------------------------------')


使用get_dummies进行one-hot编码,独热码应用前后注意color列的变化结果如下

二、实践


最后难免要变稀疏矩阵

>>> import pandas as pd
>>> s = pd.Series(list('abca'))
>>> pd.get_dummies(s)
   a  b  c
0  1  0  0
1  0  1  0
2  0  0  1
3  1  0  0
>>> s1 = ['a', 'b', np.nan]
>>> pd.get_dummies(s1)
   a  b
0  1  0
1  0  1
2  0  0
>>> pd.get_dummies(s1, dummy_na=True)
   a  b  NaN
0  1  0    0
1  0  1    0
2  0  0    1
下面这个有意思,直接C不参加,因为prefix写明了A和B参加one-hot编码。
>>> df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],
...                    'C': [1, 2, 3]})
>>> pd.get_dummies(df, prefix=['col1', 'col2'])
   C  col1_a  col1_b  col2_a  col2_b  col2_c
0  1       1       0       0       1       0
1  2       0       1       1       0       0
2  3       1       0       0       0       1

猜你喜欢

转载自blog.csdn.net/hellocsz/article/details/88315526