Change Column Names in Dataframe via list of Column Names

Question:

I have a dataframe with a ton of columns. I would like to change a list of a sub set of the column names to all uppercase.

The code below doesn’t change the column names and the other code I’ve tried produces errors:

df[cols_to_cap].columns = df[cols_to_cap].columns.str.upper()

What am I missing?

Asked By: tonytone

||

Answers:

Try the below code, this uses the rename function.

rename_dict = {}    
for each_column in list_of_cols_in_lower_case:
    rename_dict[each_column] = each_column.upper()
df.rename(columns = rename_dict , inplace = True ) #inplace to True if you want the change to be applied to the dataframe
Answered By: Arvind Reddy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.