Change column names except for certain columns

Viewed 136

Assuming I have the following dataframe

df = pd.DataFrame(
    {
            'ID': ['AB01'],
            'Col A': ["Yes"],
            'Col B': ["L"],
            'Col C': ["Yes"],
            'Col D': ["L"],
            'Col E': ["Yes"],
            'Col F': ["L"],
            'Type': [85] 
    }
    )

I want to change all column names by changing it lowercase, replace space with underscore and adding string _filled to the end of name, except for columns named in list skip = ['ID', 'Type'].

How can I achieve this? I want the end resulting dataframe to have column names as ID, col_a_filled, col_b_filled......,Type

1 Answers

You can use df.rename along with a dict comprehension to get a nice one-liner:

df = df.rename(columns={col:col.lower().replace(" ", "_")+"_filled" for col in df.columns if col not in skip})
Related