0

I'm trying to solve a system of equations: enter image description here

and I would like to apply fsolve over a pandas dataframe.

How can I do that?

this is my code:

import numpy as np
import pandas as pd
import scipy.optimize as opt
a = np.linspace(300,400,30) 
b = np.random.randint(700,18000,30) 
c = np.random.uniform(1.4,4.0,30) 
df = pd.DataFrame({'A':a, 'B':b, 'C':c})


def func(zGuess,*Params):
    x,y,z = zGuess
    a,b,c = Params
    
    eq_1 = ((3.47-np.log10(y))**2+(np.log10(c)+1.22)**2)**0.5
    eq_2 = (a/101.32) * (101.32/b)** z
    eq_3 = 0.381 * x + 0.05 * (b/101.32) -0.15
    return eq_1,eq_2,eq_3


zGuess = np.array([2.6,20.2,0.92])

df['result']= df.apply(lambda x: opt.fsolve(func,zGuess,args=(x['A'],x['B'],x['C'])))

But still not working, and I can't see the problem

JCV
  • 447
  • 1
  • 5
  • 15

1 Answers1

1

The error: KeyError: 'A' basically means he can't find the reference to 'A' Thats happening because apply doesn't default to apply on rows.

By setting the parameter 1 at the end, it will iterate on each row, looking for the column reference 'A','B',...

df['result']= df.apply(lambda x: opt.fsolve(func,zGuess,args=(x['A'],x['B'],x['C'])),1)

That however, might not give the desired result, as it will save all the output (an array) into a single column.

For that, make reference to the three columns you want to create, make an interator with zip(*...)

df['output_a'],df['output_b'],df['output_c'] = zip(*df.apply(lambda x: opt.fsolve(func,zGuess,args=(x['A'],x['B'],x['C'])),1) )

epattaro
  • 2,330
  • 1
  • 16
  • 29
  • Actually, the result is wrong, would you know why? this is the link for other questions that involves this, if you have any idea I would appreciate it: https://stackoverflow.com/questions/71680795/perform-goal-seek-in-pandas-dataframe – JCV Apr 01 '22 at 10:05
  • Hey Jennifer - if the result is wrong its either because the function is wrong, or because we are applying it wrong. My suggestion is, make a really simple function, and check it by applying it. (it should give the right result, proving that the problem is in the function) – epattaro Apr 01 '22 at 11:59
  • I guess I need boundaries, but fsolve doesn't allow them, so I have posted this question about NonConstraint here: https://stackoverflow.com/questions/71706191/solve-non-linear-equations-with-scipy-nonlinearconstraint-over-pandas-dataframe – JCV Apr 01 '22 at 12:02