Geo-x Geo-x - 1 year ago 134
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

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

But it's not very doesn't work !

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download