Skip to main content
 首页 » 编程设计

python之在 Pandas 数据框中将类转换为数字

2024年10月01日7bhlsheji

我正在做一个基于这个 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。

谢谢。

请您参考如下方法:

我想你需要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