Add Prefix to Each Column Name in Pandas DataFrame

You may use add_prefix in order to add a prefix to each column name in Pandas DataFrame:

df = df.add_prefix('my_prefix')

In the next section, you’ll see a simple example with the steps to add a prefix to your columns.

Steps to Add Prefix to Each Column Name in Pandas DataFrame

Step 1: Create the 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 the 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, columns = ['Product','Price','Discount'])
print (df)

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

Set of data

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

Let’s suppose that you’d like to add a prefix to each column name in the above DataFrame.

For example, let’s say that you want to add the prefix of ‘Sold_‘ to each column name.

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 look like this:

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, columns = ['Product','Price','Discount'])
df = df.add_prefix('Sold_')
print (df)

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

Add Prefix to Each Column Name in Pandas DataFrame

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, columns = ['Product','Price','Discount'])
df = df.rename(columns = {'Price':'Sold_Price'})
print (df)

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

Add Prefix to a Column

You may also want to check the Pandas Documentation for further information about add_prefix.