python - 在数据帧的列上使用 sklearn 的 LabelEncoder

标签 python pandas scikit-learn data-mining

如果我有一个数据框,请说 df,如果

df["levels"] = pd.Series(["low", "low", "med", "low", "med", "high"])

有没有办法将其更改为:

df["levels"] = pd.Series([0,0,1,0,1,2])

我尝试使用 preprocessing.LabelEncoder() 来转换它,但它只是折叠成 [0,1,2]。我知道我可以用 for 循环来做到这一点,但是如果已经有一些工具可以做到这一点,那就太好了任何帮助都是值得赞赏的!

最佳答案

有两种方法.. op1 类别

pd.Series(["low", "low", "med", "low", "med", "high"]).astype('category').cat.codes
Out[1454]: 
0    1
1    1
2    2
3    1
4    2
5    0
dtype: int8

op2 分解

pd.factorize(pd.Series(["low", "low", "med", "low", "med", "high"]))[0]
Out[1455]: array([0, 0, 1, 0, 1, 2], dtype=int64)

关于python - 在数据帧的列上使用 sklearn 的 LabelEncoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49593797/

相关文章:

python - 如何使 Pandas 数据框 Fortran 类型有序

python - Scikit-学习管道 : Size of predictions on test set is equal to size of training set

python - Sklearn 在线预测,批量 vs 一一

python - 如何保存在 IPython session 中编写的代码?

python - tkinter 的时间选择器

python - 在 Pandas 中使用 set_index 时出现异常

python - pandas Series.value_counts 返回相等计数字符串的不一致顺序

python - BeautifulSoup 无法使用 find_all() 提取项目

python - 如何将命令行的输出转换为脚本中的条件?

python - 使用标签将列传递给输入器的正确方法?