如何使用Pandas Dataframe列解析和评估数学表达式?

Che*_*uCR 3 python text-parsing dataframe python-3.x pandas

我想做的是解析这样一个表达式:

result = A + B + sqrt(B + 4)
Run Code Online (Sandbox Code Playgroud)

其中A和B是数据帧的列.所以我必须解析这样的表达式才能得到结果:

new_col = df.B + 4
result = df.A + df.B + new_col.apply(sqrt)
Run Code Online (Sandbox Code Playgroud)

df数据框在哪里.

我试过re.sub但是只更换像这样的列变量(不是函数)会很好:

import re

def repl(match):
    inner_word = match.group(1)
    new_var = "df['{}']".format(inner_word)
    return new_var

eq = 'A + 3 / B'
new_eq = re.sub('([a-zA-Z_]+)', repl, eq)
result = eval(new_eq)
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:

  • 有没有python库可以做到这一点?如果没有,我怎样才能以简单的方式实现这一目标?
  • 创建递归函数可能是解决方案吗?
  • 如果我使用"反向抛光表示法"可以简化解析?
  • 我必须使用该ast模块吗?

uua*_*zed 7

Pandas DataFrames确实有一个eval功能.使用您的示例等式:

import pandas as pd
# create an example DataFrame to work with
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
# define equation
eq = 'A + 3 / B'
# actual computation
df.eval(eq)

# more complicated equation
eq = "A + B + sqrt(B + 4)"
df.eval(eq)
Run Code Online (Sandbox Code Playgroud)