How to prefix the columns of a DataFrame in pandas
Overview
The add_prefix() function in pandas is used to prefix the columns of a data frame.
Syntax
The add_prefix() function takes the syntax shown below:
add_prefix("Col_")
Syntax for the add_prefix() function
Parameters
The add_prefix() function takes a single required parameter value, str, which represents the string to be prefixed or add before each label.
Return value
The add_prefix() function returns a new DataFrame with prefixed columns.
Example
# A code to illustrate the add_prefix() 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_prefix("Col_"))
Explanation
- Line 4: We import the
pandaslibrary. - Line 7: We create a DataFrame,
df. - Line 9: We print
df. - Line 12: We add the prefix
"col_"to the columns ofdf. We print the result to the console.