Geo-x Geo-x - 2 months ago 18
Python Question

Add prefix to specific columns of Dataframe

I've a DataFrame like that :

col1 col2 col3 col4 col5 col6 col7 col8
0 5345 rrf rrf rrf rrf rrf rrf
1 2527 erfr erfr erfr erfr erfr erfr
2 2727 f f f f f f


I would like to rename all columns but not col1 and col2.

So I tried to make a loop

print(df.columns)
for col in df.columns:
if col != 'col1' and col != 'col2':
col.rename = str(col) + '_x'


But it's not very efficient...it doesn't work !

Answer

You can use DataFrame.rename() method

new_names = [(i,i+'_x') for i in df.iloc[:, 2:].columns.values]
df.rename(columns = dict(new_names), inplace=True)