Evaluate a string describing operations on DataFrame columns
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 originalDataFrame.**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 libraryimport pandas as pd# creating a dataframedf = pd.DataFrame([[1,2],[3,4]],columns=list('AB'))# printing the dataframeprint(df)# performing addition of A and Bprint("Addition")print(df.eval('A + B'))# performing subtraction of A and Bprint("Subtraction")print(df.eval('A - B'))
Explanation
- Line 4: We import the
pandaslibrary. - 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 theDataFrame. We print the result to the console. - Line 19: We use the
eval()function to evaluate a string expression (subtraction) for the columns of theDataFrame. We print the result to the console.