在sklearn中将文本列转换为数字 [英] convert text columns into numbers in sklearn
问题描述
我是数据分析的新手.我正在 python Sklearn 中尝试一些模型.我有一个数据集,其中一些列有文本列.如下图,
I'm new to data analytics. I'm trying some models in python Sklearn. I have a dataset in which some of the columns have text columns. Like below,
数据集
有没有办法将这些列值转换为 pandas 或 Sklearn 中的数字?.为这些值分配数字是否正确?.如果测试数据中弹出一个新字符串怎么办?.
Is there a way to convert these column values into numbers in pandas or Sklearn?. Assigning numbers to these values will be right?. And what if a new string pops out in test data?.
请指教.
推荐答案
考虑使用标签编码 - 它通过为每个类别分配一个介于 0 和 num_of_categories-1 之间的整数来转换分类数据:
Consider using Label Encoding - it transforms the categorical data by assigning each category an integer between 0 and the num_of_categories-1:
from sklearn.preprocessing import LabelEncoder
df = pd.DataFrame(['a','b','c','d','a','c','a','d'], columns=['letter'])
letter
0 a
1 b
2 c
3 d
4 a
5 c
6 a
申请:
le = LabelEncoder()
encoded_series = df[df.columns[:]].apply(le.fit_transform)
encoded_series:
encoded_series:
letter
0 0
1 1
2 2
3 3
4 0
5 2
6 0
7 3
这篇关于在sklearn中将文本列转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!