Iterating through multiple data frames with for loop to change column names to lower case and snake case? (Pandas)

Question:

I am trying to utilize a for-loop to iterate through multiple data frames and change each df’s column names to snake case and lower case. I made a data frame list and then created a nested for-loop to iterate through the list and then iterate through each column name. The loop runs but it makes no changes to my data frame. Any help on this?

    df_list = [df_1, df_2, df_3, df_4, df_5]

    for df in df_list:
        for col in df.columns:
            col.replace(' ', '_').lower()
Asked By: Dominick Munson

||

Answers:

You didn’t assign the replaced column back, you can try

for df in df_list:
    df.rename(columns=lambda col: col.replace(' ', '_').lower(), inplace=True)
Answered By: Ynjxsjmh

To do this without inplace, since this feature will be deprecated in the future, you can try:

for df in df_list:
    df.columns=df.columns.str.lower().str.replace(' ','_')
Answered By: Danly Omil-Lima