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 takes a dictionary of {column -> new_name}:

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

You can use add_prefix or add_suffix as you need. To skip renaming some columns, you can set them as indexes and reset index after renaming.

If you want to exclude "ID" from renaming and add prefix "pre_"

df.set_index(['ID']).add_prefix("pre_").reset_index()

Derived from wwnde’s answer here : https://stackoverflow.com/a/70311963/17674957

Answered By: edzyldrm
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.