Add Suffix or Prefix

We wish to add a prefix or a suffix to the names of columns of a data frame.

In this section, we add a prefix or a suffix to the names of all columns. To only modify the names of specific columns, see Column Selection for Implicit Renaming.

Prefix

We wish to add a prefix (a substring that comes before the current column name) to the names of columns of a data frame.

In this example, we wish to add the prefix ‘B_’ to the names of all columns.

df_2 = df.add_prefix('B_')

Here is how this works:

We use the add_prefix() of Pandas data frames to append a prefix, which here is ‘B_’, to the names of the columns of the data frame. In other words, add_prefix() appends a given string to the start of the current column names.

Alternative: Implicit Renaming

df_2 = df.rename(columns=lambda x: 'B_' + x)

Here is how this works:

  • We use rename() to rename columns by applying a function to existing column names and using the output as the new column names. See Implicit Renaming.
  • In this example, we pass to rename() a lambda function lambda x: 'B_' + x that appends the desired prefix, which here is ‘B_’, to the names of all columns of the data frame df. See String Combining.

Suffix

We wish to add a suffix (a substring that comes after the current column name) to the names of columns of a data frame.

In this example, we wish to add the suffix ‘_B’ to the names of all columns.

df_2 = df.add_suffix('_B')

Here is how this works:

We use the add_suffix() of Pandas data frames to append a suffix, which here is ‘_B’, to the names of the columns of the data frame. In other words, add_suffix() appends a given string to the end of the current column names.

Alternative: Implicit Renaming

df_2 = df.rename(columns=lambda x: x + '_B')

Here is how this works:

This works similarly to the alternative solution given under Prefix except for a slight change to the lambda function to append a string to the end of column names i.e. a suffix.

PYTHON
I/O