Pandas DataFrame assign() 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.


FeFeel 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

DataFrame assign()

The assign() method adds (assigns) column(s) to an existing DataFrame.

The syntax for this method is as follows:

DataFrame.assign(**kwargs)
ParameterDescription
**kwargsThe column(s) name(s) is assigned as keywords.

For this example, a new column (accessed) adds to the DataFrame df_custs. The column fills in with random integer values. In a real-life, this column would keep track of how many times the user logged in to their account.

df_custs = pd.DataFrame({('jkende',  'Vzs*@4:kNq%)'), 
                         ('sarahJ',  '{M$*3zB~-a-W'), 
                         ('AmyKerr', '*7#<bSt?Y_Z<')}, 
                         columns=['username', 'password'], 
                         index=['user-a', 'user-b', 'user-c'])

result = df_custs.assign(accessed=pd.Series(np.random.randint(0,500,size=3)).values)
print(result)
  • Line [1] creates a DataFrame from a Dictionary of Tuples and assigns it to df_custs.
  • Line [2] assigns a new column (accessed) with random integers values to fill in this column. This output saves to result.
  • Line [3] outputs result to the terminal.

Output

df_custs

 usernamepasswordaccessed
user-a  sarahJ {M$*3zB~-a-W      155
user-b jkende Vzs*@4:kNq%)472
user-c  AmyKerr*7#<bSt?Y_Z<      354

πŸ’‘ Note: The order of the records changes.

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.