Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用所需的代码对分类列进行编码?_Python_Pandas_Scikit Learn - Fatal编程技术网

Python 如何使用所需的代码对分类列进行编码?

Python 如何使用所需的代码对分类列进行编码?,python,pandas,scikit-learn,Python,Pandas,Scikit Learn,我有这样一个数据帧: df = pd.DataFrame({'months': ['FEBRUARY', 'MARCH', 'MAY', 'DECEMBER', 'MAY']}) 我想得到: [['JANUARY', 1], ['FEBRUARY', 2], ['MARCH', 3]] 我认为这应该很容易,但当你尝试使用sklearn的这个虚拟示例时: from sklearn.preprocessing import OneHotEncoder enc = OneHotEncoder(ha

我有这样一个数据帧:

df = pd.DataFrame({'months': ['FEBRUARY', 'MARCH', 'MAY', 'DECEMBER', 'MAY']})
我想得到:

[['JANUARY', 1], ['FEBRUARY', 2], ['MARCH', 3]]
我认为这应该很容易,但当你尝试使用sklearn的这个虚拟示例时:

from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder(handle_unknown='ignore')
X = [[1,'Male'], [ 3,'Female']]
enc.fit(X)
我得到下一个错误:

 ValueError: could not convert string to float: 'Male'

提前使用Thx。

您可以使用
map

gender = {'male':1,'female':3}
df.gender.map(gender)

在使用
OneHotEncoder
之前,您需要先使用一个,但在这种情况下,
LabelEncoder
似乎是您真正想要的。在处理300万行df时,此任务是否非常昂贵?