Monday, July 18, 2022

[FIXED] How to "translate" string into an integer in python?

Issue

I have the following df:

print(df)
>>>
Marital Status       Income     Education 
  Married             66613       PhD  
  Married             12441       Bachelors 
  Single              52842       Masters Degree
  Relationship        78238       PhD
  Divorced            21242       High School
  Single              47183       Masters Degree

I'd like to convert every "String" to a corresponding number (int). E.g.

"Married" should be 1

"Single" 2

"Relationship" 3

and so on.

I still haven't tried any code yet since I haven't found any reasonable solution after googling for around 1 hour now, but I am sure that the solution is most likely incredibly simple.

Edit: grammar


Solution

This may help you to get what you need.

df['Marital Status'] = df['Marital Status'].astype('category').cat.codes

Reference: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.astype.html



Answered By - luangtatipsy
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.