You may use add_suffix in order to add a suffix to each column name in Pandas DataFrame:
df = df.add_suffix('your suffix')
In the next section, you’ll see the steps to apply the above syntax in practice.
Steps to Add Suffix to Each Column Name in Pandas DataFrame
Step 1: Create a DataFrame
To start with a simple example, let’s say that you have the following dataset that contains 3 columns:
Product | Price | Discount |
ABC | 750 | Yes |
DDD | 430 | No |
XYZ | 980 | No |
AAA | 250 | Yes |
CCC | 620 | No |
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, columns = ['Product','Price','Discount']) 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 Suffix to Each Column Name in Pandas DataFrame
Let’s suppose that you’d like to add a suffix to each column name in the above DataFrame.
For example, let’s say that you want to add the suffix of ‘_Sold‘ at the end of each column name.
In that case, you’ll need to apply this syntax in order to add the suffix:
df = df.add_suffix('_Sold')
So for our example, the complete Python code would look 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']) df = df.add_suffix('_Sold') print (df)
As you can see, the suffix of ‘_Sold‘ is now added to each column in the DataFrame:
Product_Sold Price_Sold Discount_Sold
0 ABC 750 Yes
1 DDD 430 No
2 XYZ 980 No
3 AAA 250 Yes
4 CCC 620 No
But what if you want to add a suffix to a single column (or a subset of columns) in the DataFrame?
In such a case, you may consider to rename the column/s instead.
For instance, let’s say that you want to add the suffix of ‘_Sold’ to the ‘Price’ column only. You can therefore apply the following code in Python to rename the Price column:
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':'Price_Sold'}) print (df)
You’ll now see that the suffix of ‘_Sold‘ is applied to the Price column only:
Product Price_Sold 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 to learn more about add_suffix.