離散特徵的編碼分爲兩種狀況:app
一、離散特徵的取值之間沒有大小的意義,好比color:[red,blue],那麼就使用one-hot編碼ide
二、離散特徵的取值有大小的意義,好比size:[X,XL,XXL],那麼就使用數值的映射{X:1,XL:2,XXL:3}編碼
使用pandas能夠很方便的對離散型特徵進行one-hot編碼 > code
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)
說明:對於有大小意義的離散特徵,直接使用映射就能夠了,{'XL':3,'L':2,'M':1}blog
Using the get_dummies will create a new column for every unique string in a certain column:使用get_dummies進行one-hot編碼 . get
`pd.get_dummies(df)`