Add Prefix to Each Column Name in Pandas DataFrame

To add a prefix to each column name in Pandas DataFrame:

df = df.add_prefix('my_prefix')

Steps to Add Prefix to Each Column Name in Pandas DataFrame

Step 1: Create a DataFrame

To start with a simple example, let’s suppose that you have the following dataset with 3 columns:

ProductPriceDiscount
ABC750Yes
DDD430No
XYZ980No
AAA250Yes
CCC620No

You can then create a DataFrame as follows:

import pandas as pd

data = {'Product': ['ABC', 'DDD', 'XYZ', 'AAA', 'CCC'],
        'Price': [750, 430, 980, 250, 620],
        'Discount': ['Yes', 'No', 'No', 'Yes', 'No']
        }

df = pd.DataFrame(data)

print(df)

Once you run the code in Python, you’ll get the following DataFrame:

  Product  Price  Discount
0     ABC    750       Yes
1     DDD    430        No
2     XYZ    980        No
3     AAA    250       Yes
4     CCC    620        No

Step 2: Add Prefix to Each Column Name in Pandas DataFrame

Let’s suppose that you want to add the prefix of ‘Sold_‘ to each column name in the above DataFrame.

In that case, you’ll need to apply this syntax in order to add the prefix:

df = df.add_prefix('Sold_')

So for our example, the complete Python code would be:

import pandas as pd

data = {'Product': ['ABC', 'DDD', 'XYZ', 'AAA', 'CCC'],
        'Price': [750, 430, 980, 250, 620],
        'Discount': ['Yes', 'No', 'No', 'Yes', 'No']
        }

df = pd.DataFrame(data)

df = df.add_prefix('Sold_')

print(df)

As you may see, the ‘Sold_‘ prefix was added to each column:

  Sold_Product   Sold_Price   Sold_Discount
0          ABC          750             Yes
1          DDD          430              No
2          XYZ          980              No
3          AAA          250             Yes
4          CCC          620              No

But what if you just want to add a prefix to a single column (or a subset of columns)?

In that case, you may consider to use rename instead.

For instance, let’s say that you want to add a prefix (of ‘Sold_’) to the ‘Price‘ column only. Here is the Python code that you may use to:

import pandas as pd

data = {'Product': ['ABC', 'DDD', 'XYZ', 'AAA', 'CCC'],
        'Price': [750, 430, 980, 250, 620],
        'Discount': ['Yes', 'No', 'No', 'Yes', 'No']
        }

df = pd.DataFrame(data)

df = df.rename(columns={'Price': 'Sold_Price'})

print(df)

You’ll now see that the ‘Sold_’ prefix was only added to the ‘Price’ column:

  Product   Sold_Price   Discount
0     ABC          750        Yes
1     DDD          430         No
2     XYZ          980         No
3     AAA          250        Yes
4     CCC          620         No

You can check the Pandas Documentation for further information about add_prefix.

You may also visit the following guide for the steps to add a suffix in Pandas DataFrame.