最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Python dataframe optimization with two variables - Stack Overflow

programmeradmin0浏览0评论

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) 

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) 
Share Improve this question asked Mar 28 at 14:42 nicktrentnicktrent 474 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1
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)
发布评论

评论列表(0)

  1. 暂无评论