← Back to Pandas Course | Chapter 13: Performance & Best Practices | Lesson 2 of 6

pd.eval()

pd.eval and df.eval evaluate expressions as strings, which can be faster and cleaner for big arithmetic.

In this page:

  1. pd.eval()
Syntax
python
df.eval("new_column = column1 + column2")
pd.eval("result = df.column1 + df.column2")

pd.eval()

df.eval("c = a + b") creates a column from an expression string and can avoid temporary arrays on large data. It supports arithmetic, comparisons and referencing local variables with @. Gains show mostly on large DataFrames.

Note: For small DataFrames plain Python is just as fast.

Example: pd.eval()

python
import pandas as pd

df = pd.DataFrame({"a": [1, 2, 3], "b": [10, 20, 30]})
df.eval("c = a + b * 2", inplace=True)
factor = 3
print(df.eval("a * @factor").tolist())
print(df)

# Output:
# [3, 6, 9]
#    a   b   c
# 0  1  10  21
# 1  2  20  42
# 2  3  30  63
Related Topics
Common Mistakes
  1. Expecting speed-ups on tiny data
  2. Forgetting @ for local variables
  3. Using unsupported functions in expressions
Chapter Summary
  • eval evaluates string expressions
  • Assigns new columns
  • @var references locals
  • Best on large data
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.