How to suffix the columns of a DataFrame in Pandas
Overview
The add_suffix() function in Pandas is used to suffix the columns of a DataFrame.
Syntax
The add_suffix() function takes the syntax shown below:
DataFrame.add_suffix(suffix)
Syntax for the add_prefix() function
Parameter
The add_suffix() function takes a single required parameter value suffix, which represents the string to be prefixed or added after each label.
Return value
The add_suffix() function returns a new DataFrame with prefixed/updated columns.
Code example
Let's look at the code below:
# A code to illustrate the add_suffix() function in Pandas# imporing the pandas libraryimport pandas as pd# creating a dataframedf = pd.DataFrame({'Name': ["Theo", "John", "Mosh"], 'Height': [1.83, 1.80, 1.78]})print(df)# adding prefixes to the columns of the dataframeprint(df.add_suffix("_column"))
Code explanation
- Line 4: We import the pandas library.
- Line 7: We create a DataFrame,
df. - Line 9: We print
df. - Line 12: We add the suffix
"_column"to the columns ofdf. We print the result to the console.