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'])
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
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
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']})
Now, you can do this in pandas with df.add_suffix()
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add_suffix.html
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
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'])
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
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
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']})
Now, you can do this in pandas with df.add_suffix()
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.add_suffix.html
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