Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python
dataframe
communitycreator

Evaluate a string describing operations on DataFrame columns

Onyejiaku Theophilus Chidalu

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'))
Implementing the eval() function

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
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring