Renaming selected columns in a Pandas dataframe
Let say I have below data frame:
import pandas as pd
raw_data = {'col1': [23,45,21,45,23],'col2': [3,4,5,22,3],'col3': ['y1', 'y2', 'y3', 'y1', 'y2'],'col4': ['x1', 'x2', 'x3', 'x1', 'x2']}
df = pd.DataFrame(raw_data, columns = ['col1','col2','col3','col4','col5'])
Now I want to prefix 'PRE-'
to each column names except 'col2'
and 'col4'
in a programmatic way.
Is there any method/function available to achieve this?
Thanks for your pointer
Use DataFrame.rename
with lambda function:
df = df.rename(columns = lambda x: f'PRE-{x}' if x not in ['col2','col4'] else x)
print (df)
PRE-col1 col2 PRE-col3 col4 PRE-col5
0 23 3 y1 x1 NaN
1 45 4 y2 x2 NaN
2 21 5 y3 x3 NaN
3 45 22 y1 x1 NaN
4 23 3 y2 x2 NaN
We can also use a simple list comprehension:
df.columns = [('' if col in ('col2','col4') else 'PRE-') + col for col in df.columns]
Output:
PRE-col1 col2 PRE-col3 col4 PRE-col5
0 23 3 y1 x1 NaN
1 45 4 y2 x2 NaN
2 21 5 y3 x3 NaN
3 45 22 y1 x1 NaN
4 23 3 y2 x2 NaN