Night Walker
Night Walker

Reputation: 21280

Encoding string column to numeric values by predefined rule

I have following DataFrame:

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

What is Pandas way to encode voting_result column to integers by following rule {'Bad':0, 'Good':1, 'Not Sure':2} and to get following resut

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

Thanks

Upvotes: 1

Views: 65

Answers (1)

jezrael
jezrael

Reputation: 863751

Use map by dictionary:

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

Upvotes: 5

Related Questions