2

I am trying to replace all columns in my df with prices to ints however for some reason the replace() method isn't working:

df = pd.read_csv(f_name, dtype="string")
df = df[df.columns.dropna()]
df[cols_int] = df[cols_int].replace({"[\$]": "", "[,]": ""}, regex=True)
df[cols_int] = df[cols_int].astype(int)

Error:

ValueError: invalid literal for int() with base 10: '$499,000'

I'd appreciate any help!

2
  • you need to use the replace for the string represenation of the series: df[cols_int].str.replace({"[\$]": "", "[,]": ""}, regex=True) -> place .str.in between. Commented May 5, 2021 at 22:23
  • 1
    Unfortunately I don't think this works on multiple columns Commented May 5, 2021 at 23:39

1 Answer 1

4

As of pandas 1.3, this bug should not occur anymore.


If you are still using pandas <1.3, this bug was caused by the "string" dtype, so use dtype=str or dtype="str" instead:

df = pd.read_csv(f_name, dtype=str)
#                              ---
df = df[df.columns.dropna()]
df[cols_int] = df[cols_int].replace({"[\$]": "", "[,]": ""}, regex=True)
df[cols_int] = df[cols_int].astype(int)
Sign up to request clarification or add additional context in comments.

Comments

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.