Skip to main content
 首页 » 编程设计

python之通过预定义规则将字符串列编码为数值

2025年05月04日39itcoder

我有以下数据框:

   voting_result project   scene 
    Bad          ccus      345943 
    Good         ccus      311129 
    Bad          ccus      309082 
    Bad          ccus      331613 
    Good         ccus      331615  
    Not Sure     ccus      331616    

什么是 Pandas 按照规则 {'Bad':0, 'Good':1, 'Not Sure' 将 voting_result 列编码为整数:2} 并得到以下结果

voting_result    project    scene 
        0         ccus      345943 
        1         ccus      311129 
        0         ccus      309082 
        0         ccus      331613 
        1         ccus      331615  
        2         ccus      331616 

谢谢

请您参考如下方法:

使用map通过字典:

d = {'Bad':0, 'Good':1, 'Not Sure':2} 
df['voting_result'] = df['voting_result'].map(d) 
print (df) 
   voting_result project   scene 
0              0    ccus  345943 
1              1    ccus  311129 
2              0    ccus  309082 
3              0    ccus  331613 
4              1    ccus  331615 
5              2    ccus  331616