You can use the following methods to add a prefix to column names in a pandas DataFrame:
Method 1: Add Prefix to All Column Names
df = df.add_prefix('my_prefix_')
Method 2: Add Prefix to Specific Column Names
#specify columns to add prefix to cols = ['col1', 'col3'] #add prefix to specific columns df = df.rename(columns={c: 'my_prefix_'+c 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 Prefix to All Column Names
The following code shows how to add the prefix ‘_total’ to all column names:
#add 'total_' as prefix to each column name df = df.add_prefix('total_') #view updated DataFrame print(df) total_points total_assists total_rebounds total_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 prefix ‘_total’ has been added to all column names.
Method 2: Add Prefix to Specific Column Names
The following code shows how to add the prefix ‘total_’ to only the points and assists columns:
#specify columns to add prefix to cols = ['points', 'assists'] #add _'total' as prefix to specific columns df = df.rename(columns={c: 'total_'+c for c in df.columns if c in cols}) #view updated DataFrame print(df) total_points total_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
Notice that the prefix ‘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