Adding suffix to column labels in Pandas DataFrame
Start your free 7-days trial now!
To append a suffix to column labels, use the DataFrame's add_suffix(~)
method.
Example
Consider the following DataFrame:
df = pd.DataFrame({"A":[4,5],"B":[6,7]})df
A B0 4 61 5 7
Solution
To append the suffix "C"
to each column label of df
:
df.add_suffix("C")
AC BC0 4 61 5 7
Here, add_suffix(~)
returns a new DataFrame with the added suffix and so the original df
is kept intact.
If your DataFrame is memory-heavy, then add_suffix(~)
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 suffix in-place
Consider the same df
as before:
df
A B0 4 61 5 7
Solution
To add a suffix to the column labels in-place:
df.columns = df.columns + "C"df
AC BC0 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 Series
and a scalar (string):
df.columns + "C"
Index(['AC', 'BC'], dtype='object')
We then finally assign this to be our new columns:
df.columns = df.columns + "C"
Index(['AC', 'BC'], dtype='object')