
Pandas を使用した動的評価算術。
解法
1. pd.eval() の使用
パフォーマンスの引数
次の引数を使用して、pd.eval のパフォーマンスを最適化できます:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # 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)" )
|
ログイン後にコピー
engine='numexpr'
: 高度に最適化された numexpr を使用します。 Engine.
-
parser='pandas': Pandas の演算子の優先順位と一致するデフォルトの pandas パーサーを使用します。
-
global_dict および
local_dict- : 置換用のグローバル変数とローカル変数の辞書を提供します。これにより、グローバル名前空間で変数を定義する必要がなくなります。代入とインプレース変更
ターゲット引数を使用して、pd.eval の結果を DataFrame に直接割り当てることができます。 .
2. df.eval() の使用
1 2 3 4 5 | 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)
|
ログイン後にコピー
df.query()
との比較 pd.eval は式の評価に適していますが、df.query() は条件分岐の場合により簡潔で効率的です。ブール式に基づいて DataFrame をフィルタリングするためのクエリ。
1 2 3 4 5 | # Evaluate expression in df1
result = df1. eval ( "A + B" )
# Perform variable substitution
df1. eval ( "A > @x" , local_dict={ 'x' : 5})
|
ログイン後にコピー
以上がPandas で式を動的に評価するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。