I have a dataframe with three columns: "a", "b" and "target".
I apply a function ("spreadcalc") on the whole dataframe which you can see below in the code. What I would like to do is to minimize the result of the function for each row of the dataframe by changing the values in columns "a" and "b". I would be grateful if you could help me. Thank you very much.
Here is the code:
import numpy as np
from scipy.optimize import fsolve
import scipy.optimize as optimize
def spreadcalc(df):
avrg = (df['a'] + df['b'])/2
spr = (df['b'] - df['a'])/ avrg
diff = df['target'] - spr
return diff
optimize.minimize(spreadcalc)
import numpy as np
import scipy.optimize as optimize
# Define the function with optimization variable x
def spreadcalc(x, df):
df['a'] = x[0] # Assume we're optimizing 'a'
df['b'] = x[1] # Assume we're optimizing 'b'
avrg = (df['a'] + df['b']) / 2
spr = (df['b'] - df['a']) / avrg
diff = df['target'] - spr # Difference from target
return diff**2 # Squared difference to minimize
# Sample dictionary
df = {'a': 3, 'b': 5, 'target': 10}
# Initial guess for 'a' and 'b'
x0 = [df['a'], df['b']]
# Perform optimization
result = optimize.minimize(spreadcalc, x0, args=(df,))
# Print results
print(result)