Pandas: How to Add Suffix to Column Names


You can use the following methods to add a suffix to column names in a pandas DataFrame:

Method 1: Add Suffix to All Column Names

df = df.add_suffix('_my_suffix')

Method 2: Add Suffix to Specific Column Names

#specify columns to add suffix to
cols = ['col1', 'col3']

#add suffix to specific columns
df = df.rename(columns={c: c+'_my_suffix' for c in df.columns if c in cols})

The following examples show how to use each of these methods with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23],
                   'assists': [5, 7, 7, 9, 12, 9],
                   'rebounds': [11, 8, 10, 6, 6, 5],
                   'blocks': [6, 6, 3, 2, 7, 9]})

#view DataFrame
print(df)

   points  assists  rebounds  blocks
0      25        5        11       6
1      12        7         8       6
2      15        7        10       3
3      14        9         6       2
4      19       12         6       7
5      23        9         5       9

Method 1: Add Suffix to All Column Names

The following code shows how to add the suffix ‘_total’ to all column names:

#add '_total' as suffix to each column name
df = df.add_suffix('_total')

#view updated DataFrame
print(df)

   points_total  assists_total  rebounds_total  blocks_total
0            25              5              11             6
1            12              7               8             6
2            15              7              10             3
3            14              9               6             2
4            19             12               6             7
5            23              9               5             9

Notice that the suffix ‘_total’ has been added to all column names.

Note: To add a prefix to column names, simply use add_prefix instead.

Method 2: Add Suffix to Specific Column Names

The following code shows how to add the suffix ‘_total’ to only the points and assists columns:

#specify columns to add suffix to
cols = ['points', 'assists']

#add _'total' as suffix to specific columns
df = df.rename(columns={c: c+'_total' for c in df.columns if c in cols})

#view updated DataFrame
print(df)

   points_total  assists_total  rebounds  blocks
0            25              5        11       6
1            12              7         8       6
2            15              7        10       3
3            14              9         6       2
4            19             12         6       7
5            23              9         5       9

Notice that the suffix ‘_total’ has only been added to the points and assists columns.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

How to Drop Columns in Pandas
How to Exclude Columns in Pandas
How to Change the Order of Columns in Pandas
How to Apply Function to Selected Columns in Pandas

Leave a Reply

Your email address will not be published.