Pandas DataFrame eval() Method – Be on the Right Side of Change (original) (raw)


Preparation

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

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


The eval() method evaluates a string describing the operation on DataFrame columns. This is for columns only, not specific rows or elements. This allows the eval to run arbitrary code.

🛑 Note: This can make the code vulnerable to code injection if you pass user input to this method.

The syntax for this method is as follows:

DataFrame.eval(expr, inplace=False, **kwargs)

Parameter Description
expr This parameter is the string to evaluate.
inplace If the expression contains an assignment, this determines whether to perform the operation inplace and mutate the existing DataFrame. Otherwise, a new DataFrame is returned. By default, this parameter is False.
**kwargs See the documentation here for details.

For this example, the Hockey Teams Bruins and Oilers stats will be added together.

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

result = df_teams.eval('Bruins + Oilers') print(result)

Output

0 7
1 11
2 19

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.