Add Prefix to Column Labels of DataFrame
To add a string before each column label of DataFrame in Pandas, call add_prefix() method on this DataFrame, and pass the prefix string as argument to add_prefix() method.
In this tutorial, we will learn how to add a string as prefix to column labels of DataFrame, with examples.
Syntax
The syntax of pandas DataFrame.add_prefix() method is
DataFrame.add_prefix(prefix)
where
Parameter | Value | Description |
---|---|---|
prefix | str | The string to add before each label. |
Return Value
DataFrame with updated column labels.
Examples
In the following program, we will take a DataFrame with column labels [‘1’, ‘2’]. We add prefix string ‘col_’ to the column labels of this DataFrame using DataFrame.add_prefix() method.
Example.py
import pandas as pd
df = pd.DataFrame(
{'1': [10, 20, 30], '2': [40, 50, 60]})
prefix = 'col_'
result = df.add_prefix(prefix)
print(result)
Output
col_0 col_1
0 10 40
1 20 50
2 30 60
Now, let us try with the prefix string ‘x_’.
Example.py
import pandas as pd
df = pd.DataFrame(
{'1': [10, 20, 30], '2': [40, 50, 60]})
prefix = 'x_'
result = df.add_prefix(prefix)
print(result)
Output
x_1 x_2
0 10 40
1 20 50
2 30 60
Conclusion
In this Pandas Tutorial, we learned how to add a string as prefix to column labels of DataFrame, using pandas DataFrame.add_prefix() method.