二值化
設置一個condition,把連續型的數據分類兩類。比如Age,大於30,和小於30。
from sklearn.preprocessing import Binerize as Ber
x = data_2.iloc[:,0].values.reshpe(-1,1) #提取數據
trans = Ber(threshold = 30).fit_transform(x)
trans
這是x中>30的設置為1,其他的設置為0.
標簽
有時數據可能需要對數據進行分箱化處理,或者給不同的數據設置不同的標簽。
from sklearn.preprocessing import LabelEncoder as le
l = le()
l=l.fit(y)
label =l.transform(y)
可以在l對象,用classes_屬性,查看總共有多少類。
l.classes_
array(['No', 'Unknown', 'Yes'], dtype=object)
label中就是處理過的數據。可直接寫成:
from sklearn.preprocessing import LabelEncoder
data.iloc[:,-1]=LabelEncoder().fit_transform(data.iloc[:,-1])
獨熱編碼
如果數據是有序,但不能進行計算。比如小學、中學、大學。如果用1,2,3分別進行替代。那么計算時,可能會將2視作1+1,兩個小學加起來和中學不等,因此需要將它們單獨分類組成這樣的數據:
stu_id | 小學 | 中學 | 大學 |
---|---|---|---|
1234 | 1 | ||
1235 | 1 | ||
1236 | 1 |
這種方法就叫獨熱編碼。
from sklearn.preprocessing import OneHotEncoder
enc=OneHotEncoder(categories='auto').fit(x)
使用get_feature_names() 可查看名稱:
enc.get_feature_names()
enc.get_feature_names()
得到的結果是稀疏矩陣,需要用toArray() 方法。
result=OneHotEncoder(categories='auto').fit_transform(x).toarray()
最后將結果連接到原數據中,再提取。
newdata=pd.concat([data, pd.DataFrame(result)],axis=1)