from sklearn.preprocessing import OneHotEncoder
时间: 2023-11-21 19:04:09 浏览: 79
`OneHotEncoder` is a class in the `sklearn.preprocessing` module in scikit-learn, which is a popular Python library for machine learning. It is used for converting categorical variables into binary vectors, which can be used as input for machine learning algorithms.
Here's an example of how to use `OneHotEncoder`:
```python
import numpy as np
from sklearn.preprocessing import OneHotEncoder
# create a categorical variable
categories = np.array(['A', 'B', 'C', 'A', 'B']).reshape(-1, 1)
# create an instance of OneHotEncoder
encoder = OneHotEncoder()
# fit and transform the data
one_hot = encoder.fit_transform(categories)
# print the results
print(one_hot.toarray())
```
In this example, we create a categorical variable `categories` with five values. We then create an instance of `OneHotEncoder` and fit and transform the data. The result is a binary vector for each value in the original variable.
阅读全文