replace() takes no keyword arguments, in for loop

Viewed 26026

I'm trying to convert multiple columns of dollar amount into float, and wrote the following code

    for column in wo.columns[14:21]:
        column = (column.replace( '[\$,)]','', regex=True )
                   .replace( '[(]','-',   regex=True ).replace('#NAME?','NaN', regex=True).astype(float))
    return column


And this is the error i get:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-276-f7c13cb3d0af> in <module>
      1 for column in wo.columns[14:19]:
----> 2     column = (column.replace( '[\$,)]','', regex=True )
      3                .replace( '[(]','-',   regex=True ).replace('#NAME?','NaN', regex=True).astype(float))
      4 return column
      5 

TypeError: replace() takes no keyword arguments

What might be wrong? wo is the name of the dataframe, the library i used to load the dataframe was Pandas, and when i used the code on other individual columns it worked fine, just when i used a for loop it return an error.

3 Answers

It is giving an error because it doesn't accept keyword arguments; in this case regex=True. As per the documentation, it doesn't exist. Also, .replace is for strings only, so the type of data here should be str. On the other hand, should you want to use regex, I'd recommend re.sub

Try to delete the 'regex = True' will be helpful from my case.

# df_num_key_split[name][var].replace(to_replace="[\[|\]|']|\s+|\.|\-", value='', regex=True)

After I did this, it worked.

df_num_key_split[name][var].replace("[\[|\]|']|\s+|\.|\-", '')

What type is column? print(type(column)) if its a str, it is going to use str.replace, which takes no kwargs. Try deleting regex=True.

Related