0

I have a issue with sympy, I have a data frame columns which has to be calculated with a formula and the formula is in string format I am using sympy it's taking only one value but not the series value my code

    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)

when I use this getting an error says that series has to attribute func.any suggestions?

dejanualex
  • 3,872
  • 6
  • 22
  • 37
Ram dr
  • 111
  • 5

1 Answers1

1

I did some minor changes to your code. Below is the updated version. Kindly change it as per your needs.


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))

Edited for the comment on more than one value in 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']}))

Please see it and let me know if you need more help. :)

CoderRambo
  • 417
  • 3
  • 9
  • This works well if the dataframe has one row but if the dataframe has multiple rows the same error is given. AttributeError: 'Series' object has no attribute 'func' – Ram dr Jan 18 '21 at 12:19
  • 1
    Hello @Ramdr I edited the answer for making it work for more than one value in df. I think we can use a loop to call the function for each value substitution. Kindly see the above edited answer and let me know if this helps you :) – CoderRambo Jan 18 '21 at 13:08
  • 1
    Hello @Ramdr, did this work for you ? or Need more help ? – CoderRambo Jan 19 '21 at 07:58
  • 1
    Welcome @Ramdr Happy that it worked for you :) – CoderRambo Jan 21 '21 at 11:36