Python 如何在字符串数字上使用序号编码器或热编码器

Python 如何在字符串数字上使用序号编码器或热编码器,python,machine-learning,scikit-learn,spyder,one-hot-encoding,Python,Machine Learning,Scikit Learn,Spyder,One Hot Encoding,我有一个数据集,其中有一列包含数字,如“1”、“3”、“5”、“5”等字符串。我想使用顺序编码器:1为0,2为1,3为3,依此类推。怎么做?同样在HotEncoder中,我有一个稀疏选项,而在ordinal encoder中,我没有这个选项。我需要在这里做些什么 我的代码: #independent variables-Matrix X = df.iloc[:, :-1].values #dependent variables vectors Y = df.iloc[:, -1].values

我有一个数据集,其中有一列包含数字,如“1”、“3”、“5”、“5”等字符串。我想使用顺序编码器:1为0,2为1,3为3,依此类推。怎么做?同样在HotEncoder中,我有一个稀疏选项,而在ordinal encoder中,我没有这个选项。我需要在这里做些什么

我的代码:

#independent variables-Matrix
X = df.iloc[:, :-1].values 
#dependent variables vectors
Y = df.iloc[:, -1].values 
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, OrdinalEncoder
Encoder =  OrdinalEncoder()
Z2= Encoder.fit_transform(X[:, [17]])
#X = np.hstack(( [![Z][1]][1]2, X[:,:17] , X[:,18:])).astype('float')
#handling the dummy variable trap
#X = X[:, 1:]

在您的情况下,我将使用函数而不是Sklearn

def label_encoder(column):
values = ['one', 'two', 'three', 'four', 'five'] 
new_row = []
for row in column:
    for i, ii in enumerate(values):
        if row == ii:
            new_row.append(i)
        else:
            continue
return new_row
或者您可以使用列表理解

def label_encoder(column):
values = ['one', 'two', 'three', 'four', 'five'] 
new_row = [i for row in column for (i, ii) in enumerate(values) if row==ii]
return new_row

此函数将
['1','1','2',…]数组转换为
[1,1,2,…]

谢谢!但是我得到的是列而不是行,那么一行的输入应该是什么呢?当然,我已经编辑了答案,现在的输入是一列,它通过所有行进行迭代器。让我知道它现在是否适用于您它只给了我0,但我做了一些事情,使用“替换”从字符串到数字,现在这样还可以。非常感谢。(: