2
我想准备一个包含用于分类的连续,名义和有序特征的数据集。我在下面有一些解决方法,但我想知道是否有更好的方式使用scikit-learn
的编码器?在scikit-learn中使用OneHotEncoder准备序号和名义特征
让我们看看下面的例子中数据集:
现在,类标签可以简单地通过一个标签编码器转换(分类的类别标签忽略顺序)。
from sklearn.preprocessing import LabelEncoder
class_le = LabelEncoder()
df['class label'] = class_le.fit_transform(df['class label'].values)
而且我会序功能列size
转换,像这样:
size_mapping = {
'XL': 3,
'L': 2,
'M': 1}
df['size'] = df['size'].apply(lambda x: size_mapping[x])
df
最后序color
功能:
color_mapping = {
'green': [0,0,1],
'red': [0,1,0],
'blue': [1,0,0]}
df['color'] = df['color'].apply(lambda x: color_mapping[x])
df
y = df['class label'].values
X = df.iloc[:, :-1].values
X = np.apply_along_axis(func1d= lambda x: np.array(x[0] + list(x[1:])), axis=1, arr=X)
X
array([[ 0. , 0. , 1. , 1. , 10.1],
[ 0. , 1. , 0. , 2. , 13.5],
[ 1. , 0. , 0. , 3. , 15.3]])
谢谢,看起来会更加清晰! – Sebastian 2015-02-08 20:33:38