There are two kinds of discrete feature coding, which have the meaning of size and character.
1, the characteristic does not have the size significance direct single-heat code
2, the characteristics of the size of the significance of the use of mapping code
[Python]View PlainCopy
- Import Pandas as PD
- DF = PD. DataFrame ([
- [' green ', ' M ', 10.1, ' Label1 '],
- [' Red ', ' L ', 13.5, ' Label2 '],
- [' Blue ', ' XL ', 15.3, ' Label2 ']]
- # color, label does not have size meaning, size has significance
- Df.columns = [' color ', ' size ', ' length ', ' label ']
- Df
[Python]View PlainCopy
- Size_mapping = {
- ' XL ': 3,
- ' L ': 2,
- ' M ': 1}
- df[' size ' = df[' size '].map (size_mapping)
- label_mapping = {Lab:idx for Idx,lab in enumerate (set (df[' label '))}
- df[' label '] = df[' label '].map (label_mapping)
- Df
Direct use of functions for single-hot coding
does not differentiate whether it has a size meaning
[Python]View PlainCopy
- Import Pandas as PD
- DF = PD. DataFrame ([
- [' green ', ' M ', 10.1, ' Label1 '],
- [' Red ', ' L ', 13.5, ' Label2 '],
- [' Blue ', ' XL ', 15.3, ' Label2 ']]
- # color, label does not have size meaning, size has significance
- Df.columns = [' color ', ' size ', ' length ', ' label ']
- Pd.get_dummies (DF)
Get_dummies usage:
[Python]View PlainCopy
- Import Pandas as PD
- s = PD. Series (List (' ABCA '))
- Pd.get_dummies (s)
[Python]View PlainCopy
- DF = PD. DataFrame ({' a ': [' a ', ' B ', ' a '], ' B ': [' B ', ' a ', ' C '],
- ' C ': [1, 2, 3]}
[Python]View PlainCopy
- Pd.get_dummies (DF, prefix=[' col1 ', ' col2 '])
Python discrete feature encoding