Roz
Roz

Reputation: 325

Error when converting string to integer when values are numbers in Pandas data frame

I have a column with the datatype 'object', but it actually contains numbers (408, 415, 510) with no missing values. I want to convert this to integer with the code below, but I get the error: invalid literal for int() with base 10: 'A415' (I added the first line of code after reading other posts, but I get the same error even if I drop the first line of code).

df['Area Code'] = df['Area Code'].astype(str)
df['Area Code'] = df['Area Code'].astype(int)
print(df['Area Code'].dtypes)

Upvotes: 1

Views: 761

Answers (1)

Anis R.
Anis R.

Reputation: 6912

Looks like there is a "A415" value in your column. Could be a typo?

You can check if this is the case by getting a list of the unique values in this pandas column, like below. This is a quick way of knowing if all values look alright.

df['Area Code'].unique()

Upvotes: 2

Related Questions