2017-06-05 58 views
1

我想使用sklearn熱門編碼器進行狀態的熱編碼。這裏是我的熊貓數據框:一個使用sklearn的國家的熱門編碼

State 
0 FL 
1 CA 
2 MD 
3 NY 
4 NY 
5 NY 
6 NY 

我寫道:

from sklearn.preprocessing import OneHotEncoder 

enc=OneHotEncoder(sparse=False) 
enc.fit(data) 

而這裏的錯誤:

--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-78-a0b336acd757> in <module>() 
----> 1 enc.fit(data) 

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/preprocessing/data.py in fit(self, X, y) 
    1842   self 
    1843   """ 
-> 1844   self.fit_transform(X) 
    1845   return self 
    1846 

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/preprocessing/data.py in fit_transform(self, X, y) 
    1900   """ 
    1901   return _transform_selected(X, self._fit_transform, 
-> 1902         self.categorical_features, copy=True) 
    1903 
    1904  def _transform(self, X): 

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/preprocessing/data.py in _transform_selected(X, transform, selected, copy) 
    1695  X : array or sparse matrix, shape=(n_samples, n_features_new) 
    1696  """ 
-> 1697  X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES) 
    1698 
    1699  if isinstance(selected, six.string_types) and selected == "all": 

/anaconda/envs/env3_insight/lib/python3.6/site-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) 
    380          force_all_finite) 
    381  else: 
--> 382   array = np.array(array, dtype=dtype, order=order, copy=copy) 
    383 
    384   if ensure_2d: 

ValueError: could not convert string to float: 'NY' 

我不明白。我認爲做一個熱門編碼的重點就是從分類,通常是字符串信息轉換爲數字...爲什麼它說我不能將字符串轉換爲浮點數,然後呢?

+0

首先,您需要使用LabelEncoder。 – ayhan

+0

OneHotEncoder,[文檔建議](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html)只接受數字數據。首先爲您的數據分配一些數值,如'FL'爲1,'CA'爲2等,然後使用OneHotEncoding。按照@ayhan的建議將字符串轉換爲數字使用LabelEncoder。 –

回答

0

熊貓數據框有一個內置選項來創建一個熱門編碼,使用get_dummies method

在你的榜樣

data = pd.DataFrame(['FL','CA','MD','NY','NY','NY','NY'], columns= ['State']) 

pd.get_dummies(data.State) 

將導致:

CA FL MD NY

0 0 1 0 0

1 1 0 0 0

2 0 0 1 0

3 0 0 0 1

4 0 0 0 1

5 0 0 0 1

6 0 0 0 1

相關問題