replace() takes no keyword arguments, in for loop

23,031

Solution 1

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

Solution 2

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+|\.|\-", '')

Share:
23,031

Related videos on Youtube

Mapo Tofu
Author by

Mapo Tofu

Updated on December 17, 2020

Comments

  • Mapo Tofu
    Mapo Tofu over 3 years

    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.

    • Michael Butscher
      Michael Butscher over 4 years
      If you use an external library add it to the tags of the question. And show definition of "wo".
    • fabianegli
      fabianegli over 4 years
      If you use pandas, you need to apply the replace to the str of the DataFrame or Series like so: column.str.replace. The str part has to be added every time before the replace function.
    • fabianegli
      fabianegli over 4 years
      Also, pandas regex=True is the default and does not need to be specified.