I want to rename a selected portion of columns with a lambda function using rename
import pandas as pd
df = pd.DataFrame({'pre_col1': [1, 2],
                   'pre_col2': [3, 4],
                   'pre_col3': [ 3,  29],
                   'pre_col4': [94, 170],
                   'pre_col5': [31, 115]})
# This works but it renames all of them
# df.rename(columns=lambda x: x.replace('pre_', ''))
# I'm only wanting to edit and rename a selection
df.iloc[:, 2:5] = (df.iloc[:, 2:5]
                     .rename(columns=lambda x: x.replace('pre_', '')))
print(df)
This produces
   pre_col1  pre_col2  pre_col3  pre_col4  pre_col5
0       1.0       3.0       NaN       NaN       NaN
1       2.0       4.0       NaN       NaN       NaN
I know there are many ways to rename columns. I've read here, here, and here.
But why isn't this way working? And why does it fill the columns i'm trying to change with NaNs ??
 
     
     
    