如何在 python 中替换数学方程式中的数据框列?

How to substitute data frame columns in mathematics equations in python?

我对 sympy 有疑问, 我有一个数据框列,必须用公式计算,公式是字符串格式 我正在使用 sympy 它只取一个值而不是系列值 我的代码

    import sympy
    def eval_eqn(eqn,in_dict):
        sub = {sympy.symbols(key):item for key,item in in_dict.items()}
        ans = sympy.simplify(eqn).evalf(subs = sub)
        
    
        return ans
    in_dict = {"x": df['bike_count'],"y":df['car_count'],"z":df['flight_count']}
    eqn = "x+y+z"
    eval_eqn(eqn,in_dict)

当我使用这个时出现错误,说该系列必须归因于 func。有什么建议吗?

我对您的代码做了一些小改动。以下是更新后的版本。请根据您的需要进行更改。


from sympy import *
import pandas as pd 
  
# initialize list of lists 
data = [[10, 15, 14]] 
  
# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['bike_count', 'car_count','flight_count']) 
print(df)
def eval_eqn(eqn,in_dict):
    sub = {symbols(key):item for key,item in in_dict.items()}
    ans = simplify(eqn).evalf(subs = sub)
    

    return ans
in_dict = {"x": df['bike_count'],"y":df['car_count'],"z":df['flight_count']}
x, y, z = symbols("x y z")
eqn = x+y+z
print(eval_eqn(eqn,in_dict))

编辑了对 df 中多个值的评论

from sympy import *
import pandas as pd 
  
# initialize list of lists 
data = [[10, 15, 14],[20, 15, 14]] 
  
# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['bike_count', 'car_count','flight_count']) 
print(df)
def eval_eqn(eqn,in_dict):
    sub = {symbols(key):item for key,item in in_dict.items()}
    print(sub)
    #exit()
    ans = simplify(eqn).evalf(subs = sub)
    

    return ans
in_dict = {"x": df['bike_count'],"y":df['car_count'],"z":df['flight_count']}
#print("ddd",in_dict)
x, y, z = symbols("x y z")
eqn = x+y+z
for index, row in df.iterrows():
    print({"x": row['bike_count'],"y":row['car_count'],"z":row['flight_count']})
    print(eval_eqn(eqn,{"x": row['bike_count'],"y":row['car_count'],"z":row['flight_count']}))

请查看,如果您需要更多帮助,请告诉我。 :)