0
0
Pandasdata~5 mins

eval() for expression evaluation in Pandas

Choose your learning style9 modes available
Introduction

The eval() function in pandas helps you quickly calculate or filter data using simple expressions. It makes working with data easier and faster.

You want to add a new column based on calculations from other columns.
You need to filter rows using a condition involving multiple columns.
You want to update values in a column using an expression.
You want to perform quick math operations on columns without writing loops.
Syntax
Pandas
pandas.eval(expr, inplace=False, engine='python', parser='pandas', local_dict=None, global_dict=None)

expr is the expression string you want to evaluate.

You can use column names directly in the expression.

Examples
Adds columns A and B from the DataFrame.
Pandas
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
result = pd.eval('df.A + df.B')
print(result)
Creates a boolean mask where x is greater than 15 and y is less than 3.
Pandas
df = pd.DataFrame({'x': [10, 20, 30], 'y': [1, 2, 3]})
mask = pd.eval('df.x > 15 and df.y < 3')
print(mask)
Adds a new column 'c' by multiplying columns 'a' and 'b'.
Pandas
df = pd.DataFrame({'a': [5, 6], 'b': [7, 8]})
df['c'] = pd.eval('df.a * df.b')
print(df)
Sample Program

This program calculates total sales by multiplying price and quantity using eval(). Then it filters rows where total sales are more than 400.

Pandas
import pandas as pd

# Create a simple DataFrame
sales = pd.DataFrame({
    'price': [100, 200, 300],
    'quantity': [1, 3, 2]
})

# Calculate total sales using eval
sales['total'] = pd.eval('sales.price * sales.quantity')

# Filter rows where total sales are greater than 400
high_sales = sales[pd.eval('sales.total > 400')]

print(sales)
print('\nRows with total sales > 400:')
print(high_sales)
OutputSuccess
Important Notes

eval() can be faster than normal pandas operations for big data.

Be careful with complex expressions; test them step-by-step.

Summary

eval() lets you write math or logic expressions as strings to work with pandas data.

It helps add columns, filter data, or update values easily.

Use it to make your code shorter and sometimes faster.