Trusted answers to developer questions

Evaluate a string describing operations on DataFrame columns

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Overview

The eval() function is used to perform an evaluation to a string describing operations on the columns of a given DataFrame.

Syntax

DataFrame.eval(expr, inplace=False, **kwargs)[source]
Syntax for the eval() function in pandas

Parameters

  • expr: This is a string expression to be evaluated.
  • inplace: This takes a boolean value indicating if the operation is to be performed on the original DataFrame.
  • **kwargs: These are the keywords that have no effect but may be accepted for compatibility with NumPy.

Return value

This function returns a DataFrame holding the results from the evaluation.

Example

# A code to illustrate the cummax() function in Pandas
# importing the pandas library
import pandas as pd
# creating a dataframe
df = pd.DataFrame([[1,2],
[3,4]],
columns=list('AB'))
# printing the dataframe
print(df)
# performing addition of A and B
print("Addition")
print(df.eval('A + B'))
# performing subtraction of A and B
print("Subtraction")
print(df.eval('A - B'))

Explanation

  • Line 4: We import the pandas library.
  • Lines 7–9: We create a dataframe, df.
  • Line 11: We print the dataframe, df.
  • Line 15: We use the eval() function to evaluate a string expression (addition) for the columns of the DataFrame. We print the result to the console.
  • Line 19: We use the eval() function to evaluate a string expression (subtraction) for the columns of the DataFrame. We print the result to the console.

RELATED TAGS

pandas
python
dataframe

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
Did you find this helpful?