python将离散数据数值化
时间: 2023-12-11 19:05:05 浏览: 94
在Python中,可以使用LabelEncoder和OneHotEncoder来将离散数据数值化。
LabelEncoder将每个离散值映射到一个唯一的整数。例如,如果有一个离散特征"颜色",它有红、绿、蓝三个取值,使用LabelEncoder将红映射为0,绿映射为1,蓝映射为2。
示例代码:
```python
from sklearn.preprocessing import LabelEncoder
colors = ['red', 'green', 'blue', 'blue', 'red', 'green', 'red']
encoder = LabelEncoder()
encoded_colors = encoder.fit_transform(colors)
print(encoded_colors) # 输出 [2 1 0 0 2 1 2]
```
OneHotEncoder将每个离散值映射到一个长度为n的二进制向量,其中n是离散值的个数。例如,如果有一个离散特征"颜色",它有红、绿、蓝三个取值,使用OneHotEncoder将红映射为[1, 0, 0],绿映射为[0, 1, 0],蓝映射为[0, 0, 1]。
示例代码:
```python
from sklearn.preprocessing import OneHotEncoder
import numpy as np
colors = ['red', 'green', 'blue', 'blue', 'red', 'green', 'red']
encoder = OneHotEncoder(sparse=False)
encoded_colors = encoder.fit_transform(np.array(colors).reshape(-1, 1))
print(encoded_colors) # 输出 [[0. 0. 1.]
# [0. 1. 0.]
# [1. 0. 0.]
# [1. 0. 0.]
# [0. 0. 1.]
# [0. 1. 0.]
# [0. 0. 1.]]
```
注意,使用OneHotEncoder时需要将原始数据转换为二维数组。
阅读全文
相关推荐
















