Adding prefix to column labels in Pandas DataFame
Start your free 7-days trial now!
To prepend a prefix to column labels, use the DataFrame's add_prefix(~)
method.
Example
Consider the following DataFrame:
df = pd.DataFrame({"A":[4,5],"B":[6,7]})df
A B0 4 61 5 7
Solution
To prepend the prefix "C"
to each column label of df
:
df.add_prefix("C")
CA CB0 4 61 5 7
Here, add_prefix(~)
returns a new DataFrame with the added prefix and so the original df
is kept intact.
If your DataFrame is memory-heavy, then add_prefix(~)
is not ideal since the method allocates new memory for the returned DataFrame. To perform the same operation in-place, that is, directly modifying the original DataFrame without creating a new DataFrame, refer to the section below.
Adding a prefix in-place
Consider the same df
as before:
df
A B0 4 61 5 7
Solution
To add a prefix to the column labels in-place:
df.columns = "C" + df.columnsdf
CA CB0 4 61 5 7
Explanation
Here, df.columns
returns a Series
like so:
df.columns
Index(['A', 'B'], dtype='object')
We then use the broadcasting technique of adding a scalar (string) and a Series
:
"C" + df.columns
Index(['CA', 'CB'], dtype='object')
We then finally assign this to be our new columns:
df.columns = "C" + df.columns
Index(['CA', 'CB'], dtype='object')