Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add prefix to specific columns of Dataframe

Tags:

python

pandas

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 !

like image 770
Geo-x Avatar asked Sep 29 '16 14:09

Geo-x


1 Answers

You can use the DataFrame.rename() method

new_names = [(i,i+'_x') for i in df.iloc[:, 2:].columns.values]
df.rename(columns = dict(new_names), inplace=True)
like image 59
A.Kot Avatar answered Oct 12 '22 20:10

A.Kot