Replace function not accepting list as argument - pandas. Getting error TypeError: replace() argument 1 must be str, not list

I have searched many past questions but could not find answer to my problem!

I am trying to replace the column names of a data frame by passing two lists. First list (current column names) as to_replace argument and second list as value (new column names). According to the df.replace documentation, one can pass lists:

  • list of str, regex, or numeric:

    - First, if `to_replace` and `value` are both lists, they
      **must** be the same length.
    - Second, if ``regex=True`` then all of the strings in **both**
      lists will be interpreted as regexs otherwise they will match
      directly. This doesn't matter much for `value` since there
      are only a few possible substitution regexes you can use.
    - str, regex and numeric rules apply as above.
    

My code is:

CurrentColNames=list(df.columns)

NewColNames=['Hello','Hi', ...'Bye'] #Just an example. Lists are of same size and type. 

df.rename(columns={c: c.replace(CurrentColNames,NewColNames) for c in df.columns},inplace=True)

I am geeting error:

TypeError: replace() argument 1 must be str, not list

But documentation said, one can pass lists! Am i missing something? Any help?!

728x90

1 Answers Replace function not accepting list as argument - pandas. Getting error TypeError: replace() argument 1 must be str, not list

.replace is used for replacing a DataFrame's values, which are distinct from the DataFrame's column names. @sacul is right - the easiest way to do what you want to do, is to simply replace the .columns attribute with a new list:

df.columns = NewColNames

If you have a dictionary mapping current names to new names (let's call it current_to_new, you could also use .rename:

df = df.rename(columns=current_to_new)

4 months ago