Convert dtype from object to int

Question:

I have

df = df['enrolment'].astype(str).astype(int)

changing from str to int but it doesn’t work. Instead, it says:

invalid literal for int() with base 10: '5,424'

I want to change from object to int. How do I solve this?

df=pd.read_csv('C:/data/intake-enrolment-and-graduates-by-course.csv',sep=',')
print(df['enrolment'].dtypes)
Asked By: Ritchie

||

Answers:

Given the invalid literal error, the conversion from str to int fails as you have decimal commas in your numbers. These are nice for readability but throw a wrench into the conversion to integer. Deleting the commas does the trick.

In particular, use

df['enrollment'] = df['enrollment'].str.replace(',', '').astype(int)
Answered By: 7shoe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.