2016-01-21 68 views
1

我是數據分析的新手。我想在python sklearn中使用一些模型。我有一個數據集,其中一些列有文本列。如下圖所示,將文本列轉換爲sklearn中的數字

dataset

有沒有辦法將這些列中的值轉換爲數字轉換成大熊貓或sklearn?爲這些值分配數字是正確的。如果在測試數據中彈出一個新的字符串呢?

請指教。

+0

考慮使用[get_dummies](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dumm ies.html)函數在熊貓中可用。忽略測試數據中遇到的所有新值,不能使用訓練期間未看到的值。 – shanmuga

+0

我正在考慮使用它。但一些列有許多獨特的值(高達400+)。 –

回答

0

您可以使用分類數據類型將它們轉換爲整數代碼。

column = column.astype('category') 
column_encoded = column.cat.codes 

只要使用使用具有足夠深樹一樹的基於模型,如GradientBoostingClassifier(max_depth=10),你的模型應該能夠再次打出的類別。

0

考慮使用標籤編碼 - 它由0之間分配每個類別的一個整數變換的分類數據和所述num_of_categories-1:

from sklearn.preprocessing import LabelEncoder 
df = pd.DataFrame(['a','b','c','d','a','c','a','d'], columns=['letter']) 

    letter 
0  a 
1  b 
2  c 
3  d 
4  a 
5  c 
6  a 

應用:

le = LabelEncoder() 
encoded_series = df[df.columns[:]].apply(le.fit_transform) 

encoded_series:

letter 
0 0 
1 1 
2 2 
3 3 
4 0 
5 2 
6 0 
7 3