首頁 > 後端開發 > Python教學 > 如何動態評估 Pandas 中的表達式?

如何動態評估 Pandas 中的表達式?

Patricia Arquette
發布: 2024-11-15 10:07:02
原創
448 人瀏覽過

How Can I Dynamically Evaluate Expressions in Pandas?

Evaluating Expressions Dynamically with Pandas

Problem Statement

You want to perform dynamic operations on DataFrames using pd.eval, including variable substitution and complex arithmetic.

Solution

1. Using pd.eval()

# Import necessary libraries
import pandas as pd
import numpy as np

# Create sample DataFrames
np.random.seed(0)
df1 = pd.DataFrame(np.random.choice(10, (5, 4)), columns=list('ABCD'))
df2 = pd.DataFrame(np.random.choice(10, (5, 4)), columns=list('ABCD'))

# Evaluate expression using a variable
x = 5
result = pd.eval("df1.A + (df1.B * x)")

# Alternatively, assign the result to a new column
pd.eval("df2['D'] = df1.A + (df1.B * x)")
登入後複製

Arguments for Performance

The following arguments can be used to optimize pd.eval performance:

  • engine='numexpr': Use the highly optimized numexpr engine.
  • parser='pandas': Use the default pandas parser, which aligns with Pandas' operator precedence.
  • global_dict and local_dict: Supply dictionaries of global and local variables for substitution. This avoids the need to define variables in the global namespace.

Assignment and in-place Modification

You can assign the result of pd.eval directly to a DataFrame using the target argument.

df3 = pd.DataFrame(columns=list('FBGH'), index=df1.index)
pd.eval("df3['B'] = df1.A + df2.A", target=df3)

# In-place modification
pd.eval("df2.B = df1.A + df2.A", target=df2, inplace=True)
登入後複製

2. Using df.eval()

# Evaluate expression in df1
result = df1.eval("A + B")

# Perform variable substitution
df1.eval("A > @x", local_dict={'x': 5})
登入後複製

Comparison with df.query()

While pd.eval is suitable for evaluating expressions, df.query() is more concise and efficient for conditional queries, as it filters the DataFrame based on a Boolean expression.

# Query df1
df1.query("A > B")
登入後複製

以上是如何動態評估 Pandas 中的表達式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板