How to add suffix to column names except some columns?

Question:

Given pandas DataFrame, how can I add the suffix “_old” to all columns except two columns Id and Name?

import pandas as pd
data = [[1,'Alex',22,'single'],[2,'Bob',32,'married'],[3,'Clarke',23,'single']]
df = pd.DataFrame(data,columns=['Id','Name','Age','Status'])
Asked By: ScalaBoy

||

Answers:

Using map

df.columns=df.columns.map(lambda x : x+'_old' if x !='Id' and x!='Name' else x)
df
Out[181]: 
   Id    Name  Age_old Status_old
0   1    Alex       22     single
1   2     Bob       32    married
2   3  Clarke       23     single
Answered By: BENY

You can reassign the dataframe’s columns:

>>> df
   Id    Name  Age   Status
0   1    Alex   22   single
1   2     Bob   32  married
2   3  Clarke   23   single
>>> 
>>> keep_same = {'Id', 'Name'}
>>> df.columns = ['{}{}'.format(c, '' if c in keep_same else '_old')
...:               for c in df.columns]
>>>
>>> df
   Id    Name  Age_old Status_old
0   1    Alex       22     single
1   2     Bob       32    married
2   3  Clarke       23     single
Answered By: timgeb

You can use the rename method which gets a dictionary of {column -> new_name}:

df = df.rename(columns={c: c+'_old' for c in df.columns if c not in ['Id', 'Name']})
Answered By: Max Segal
Answered By: Anna DW
df.rename(columns = lambda col: f"{col}_old" 
                                if col not in ('Name', 'Id') 
                                else col
          )

   Id    Name  Age_old Status_old
0   1    Alex       22     single
1   2     Bob       32    married
2   3  Clarke       23     single

Answered By: sammywemmy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.