在pandas数据框中将类转换为数字

8
I'正在完成一个基于 Kaggle 数据集的项目: https://www.kaggle.com/rush4ratio/video-game-sales-with-ratings/data。我需要将数据放入 kNN 模型中,但是在目前的状态下无法实现,因为我需要将字符串值转换为整数。
使用 get_dummies 并不理想,因为数据集中有大量的分类数据,会创建成千上万的列。我正在寻找一种将字符串转换为数字表示的方法,例如:
Platform || Critic_Score || Publisher || Global_Sales
Wii      ||      73      ||  Nintendo ||  53
Wii      ||      86      ||  Nintendo ||  60
PC       ||      80      ||Activision ||  30
PS3      ||      74      ||Activision ||  35
Xbox360  ||      81      ||   2K      ||  38

我想将它转化为:
Platform || Critic_Score || Publisher || Global_Sales
  1      ||      73      ||     1     ||  53
  1      ||      86      ||     1     ||  60
  2      ||      80      ||     2     ||  30
  3      ||      74      ||     2     ||  35
  4      ||      81      ||     3     ||  38

我正在使用Python 3。谢谢。
2个回答

15

我认为你需要使用factorize函数:

df['Platform'] = pd.factorize(df['Platform'])[0] + 1
df['Publisher'] = pd.factorize(df['Publisher'])[0] + 1
print (df)
   Platform  Critic_Score  Publisher  Global_Sales
0         1            73          1            53
1         1            86          1            60
2         2            80          2            30
3         3            74          2            35
4         4            81          3            38

cols = ['Platform', 'Publisher']
df[cols] = df[cols].apply(lambda x: pd.factorize(x)[0] + 1)

print (df)
   Platform  Critic_Score  Publisher  Global_Sales
0         1            73          1            53
1         1            86          1            60
2         2            80          2            30
3         3            74          2            35
4         4            81          3            38

感谢您的帮助,我尝试了这个,但是我收到了以下错误信息:C:\Users\Josh Charig\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy """Entry point for launching an IPython kernel.另外,如果真正的数据框中有许多包含文本的列,是否有一种方法可以一次更改它们所有的列? - jceg316
请检查编辑后的答案。我猜问题出在this上,所以需要copy - jezrael

7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接