2

.dtypes shows the "Amount" column is by default an object

So I tried this,

df['Amount'] = df['Amount'].astype(int)

I got this error,

ValueError: invalid literal for int() with base 10: '3,448.91'
3
  • In your own words, given that '3,448.91' appears in the column, what do you think should be the int result for that? Why? In your own words, what does int mean? Commented Nov 25, 2021 at 15:48
  • It's a function that converts a value to an integer Commented Nov 25, 2021 at 15:55
  • In your own words, what is an integer? Commented Nov 25, 2021 at 15:57

1 Answer 1

1

The issue is that your column contains a comma(,). First replace that with empty string, then convert the type to int.

df['Amount'] = df['Amount'].str.replace(',', '').astype(float)

If you want to round off the values and convert to int, do this:

df['Amount'] = df['Amount'].str.replace(',', '').astype(float).round().astype(int)
Sign up to request clarification or add additional context in comments.

6 Comments

This will not fix the problem, as '3448.91' still cannot be converted to integer. There are two things OP could possibly want: to convert to float instead, or to round or truncate the value to an integer according to some rule. The question should not be answered until that is resolved.
I downvoted, because I knew you would still get that error.
@Pythonaccount Try the answer now.
@KarlKnechtel Please check my updated answer. I've handled both the cases you pointed out.
@Mayank Porwal I must be doing something really stupid. First first line above errors as "AttributeError: Can only use .str accessor with string values!". However if I instead create a new column instead of overwriting Amount, df['New_Amount'] = .... It works fine.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.