Ritchie
Ritchie

Reputation: 11

Convert dtype from object to int

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)

Upvotes: 0

Views: 655

Answers (1)

7shoe
7shoe

Reputation: 1506

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)

Upvotes: 1

Related Questions