使用sklearn的国家的一个热编码

时间:2017-06-05 04:52:37

标签: python pandas scikit-learn one-hot-encoding

我正在尝试使用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'

我不明白。我认为进行热编码的重点是将分类,通常是字符串,信息转换为数字...为什么它说我不能将字符串转换为浮点数呢?

1 个答案:

答案 0 :(得分:1)

Pandas数据框有一个内置选项,可以使用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