Che*_*uCR 3 python text-parsing dataframe python-3.x pandas
我想做的是解析这样一个表达式:
result = A + B + sqrt(B + 4)
其中A和B是数据帧的列.所以我必须解析这样的表达式才能得到结果:
new_col = df.B + 4
result = df.A + df.B + new_col.apply(sqrt)
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)
所以,我的问题是:
ast模块吗?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)
| 归档时间: | 
 | 
| 查看次数: | 1634 次 | 
| 最近记录: |