想知道ScikitLearn中的编码算法吗

2024-09-22 16:37:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编码一个序数变量。例如,顾客满意度分为4个等级,非常好,好,中等,差。我试过在scikit-learn库中使用LabelEncoder,但是编码返回的值非常好,应该是最好的,不是3而是2

我想知道是否可以为LabelEncoder方法中的每个级别设置特定的值


Tags: 方法编码scikit级别learn序数labelencoder
1条回答
网友
1楼 · 发布于 2024-09-22 16:37:47

您可以使用^{}并提供自己的映射表。映射表的格式是一个列表列表,其中第n个列表包含输入数据第n列中的值

from sklearn.preprocessing import OrdinalEncoder
import random
import pandas as pd

# the categorical values in the right order
satisfaction = ['Poor', 'Moderate', 'Good', 'Very Good']

# create the mapping list
mapping = [satisfaction]

# create some random data but reproducible data
random.seed(42)
X = pd.DataFrame({'satisfaction': [random.choice(satisfaction) for _ in range(25)]})
print(X)
0          Poor 
1          Poor 
2          Good 
3          Moderate 
4          Moderate 
5          Moderate 

[...]

# create the encoder
enc = OrdinalEncoder(categories=mapping)

# transform your data
print(enc.fit_transform(X))
[[0.]
 [0.]
 [2.]
 [1.]
 [1.]
 [1.]
 ...
]

相关问题 更多 >