Pandas DataFrame add_prefix() Method

Rate this post

Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy as np 

DataFrame add_prefix()

The add_prefix() method adds a specified string to the prefix (beginning) of a DataFrame/Series row or column label(s).

The syntax for this method is as follows:

DataFrame.add_prefix(prefix)
ParameterDescription
prefixIf working with a DataFrame, the prefix is pre-pended to the column label(s). If a Series, the row label(s) is the same.

For this example, the string 'Team_' is added as a prefix to the label(s) along the column axis.

df_teams = pd.DataFrame({'Bruins':   [4, 5, 9],
                         'Oilers':   [3, 6, 10],
                         'Leafs':    [2, 7, 11],
                         'Flames':   [1, 8, 12]},
                         index=['Ŵins', 'Losses', 'Ties'])

result = df_teams.add_prefix('Team_')
print(result)
  • Line [1] creates a DataFrame from a dictionary of lists, sets the index, and saves it to df_teams.
  • Line [2] uses the add_prefix() method to prefix the string at the appropriate spot. This output saves to the result variable.
  • Line [3] outputs the result to the terminal.

Output

 Team_Bruins Team_Oilers Team_Leafs Team_Flames
Wins4321
Losses5678
Ties9101112

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.