Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to "translate" string into an integer in python?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading