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


我不明白我认为进行热编码的全部目的是将分类信息(通常是字符串)转换为数字...为什么说不能将字符串转换为浮点型呢?

最佳答案

熊猫数据框具有内置选项,可使用get_dummies method创建一种热编码。

在您的示例中:

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

pd.get_dummies(data.State)


将导致:


  加利福尼亚州
  
  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

关于python - 一种使用sklearn的国家/地区热编码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44361869/

10-13 08:37