循环访问数据框并创建优化功能

时间:2014-09-09 01:06:29

标签: function optimization pandas

我在python中编写了一个小代码,它运行正常。

import numpy as np
import pandas as pd
from scipy.optimize import minimize



"""define power and coefficients"""

power = 0.6
coefficient = 5.6

"""define objective function"""

def func(x,sign=1.0):
    return sign*sum(coefficient*(x[0:]**power))

""" define constraints"""

cons = ({'type': 'ineq', 'fun': lambda x:  x[1] - 2 * x[1] + 2},
    {'type': 'ineq', 'fun': lambda x: -x[2] - 2 * x[1] + 6},
    {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})

""" define bounds"""

bnds = ((0.7, 1.3), (0.7, 1.3), (0.7,1.3))

"""initial values of the variables"""

x0 = np.array([1.1, 3.9,5.6])

"""run the optimization  algorithm"""

res = minimize(func, x0, method='SLSQP',bounds = bnds,constraints=cons,
           options={'disp': True})

"""print the results"""

print(res.x)

此代码包含目标函数

def func(x,sign=1.0):
    return sign*sum(coefficient*(x[0:]**power))

,初始值为

x0 = np.array([1.1, 3.9,5.6])

但它都是硬编码的。我想在运行时形成它们。

即。我有一个csv文件,我会读到一个数据帧CSV文件的结构是

DV_Name Investment
DV1     1.2
DV2     1.2
DV3     1.3
DV4     1.2
DV5     1.2
DV6     4.5
DV7     1.2
DV8     2.7
DV9     1.2
DV10    1.2

我使用了pd.DataFrame.from_csv

我需要做什么才能使我的目标函数以coeff*(DV1 ^ power + DV2^power + DV3^power ......DV10^power)的形式和我的初始值数组x0作为投资值,即投资(0),投资(1)....等等。

2 个答案:

答案 0 :(得分:0)

您可以使用pow(exponent)提升DataFrame的列,如下所示:

>>> import pandas as pd
>>> df = pd.DataFrame({'foo':[1,2,3,4], 'bar':[5,6,7,8]})
>>> df['foo'].pow(2) # raise all elements of the column 'foo' to the power 2
0     1
1     4
2     9
3    16
Name: foo, dtype: int64

或者您可以像this SO answer

一样df['bar'] ** 2

然后,您可以使用sum()对这一列的元素进行求和,如下所示:

>>> df['foo'].pow(2).sum()
30

这应该足以让你开始了!

答案 1 :(得分:0)

我能够解决这个问题:

import pandas as pd
import numpy as np
from scipy.optimize import minimize
pd.set_option('display.mpl_style', 'default') 

“”“将输入文件读入数据框”“”

df = pd.DataFrame.from_csv('C:\Users\prashant.mudgal\Downloads\Test.csv')

“”DV的子集“”“

dv= df['DV']

“”“目标功能”“” “”“功率附加功能”“” “”已添加“sign = 1.0以实现最大化”“” “”系数的相应矩阵,功率是用“”

def func(dv,sign=1.0) :
return sign*(sum(df['Coefficient'].values[0:]*dv[0:]**df['Power'].values[0:]))

“”“定义边界”“”

bnds = ((0.7, 1.3),(0.7, 1.3),(0.7,1.3),(0.7,1.3),(0.7,1.3),(0.7,1.3),(0.7,1.3),    (0.7,1.3),(0.7,1.3))

“”“bnds =((df ['LB']。values,df ['UB']。values))”“”

“”“定义约束”“”

cons = ({'type': 'ineq', 'fun': lambda x:  dv[1] - 2 * dv[1] + 2},
    {'type': 'ineq', 'fun': lambda x: -dv[2] - 2 * dv[1] + 6},
    {'type': 'ineq', 'fun': lambda x: -dv[0] + 2 * dv[1] + 2})

“”“使用最小二乘法总和运行优化”“” “”s.values是csv文件中投资列给出的初始估计值“”

res = minimize(func, df['Inv'].values,args=(-1.0,),method='SLSQP',bounds=bnds,
           options={'disp': True})

“”“打印结果”“”

print (res)

但我有一个新问题,我创建的边界,它们是硬编码的,我不希望这样。我希望从数据框或文件中读取它们 我的文件有2列

upperbound  Lowerbound
1.3               0.7
1.3               0.7
1.3               0.7.........

现在我想在阅读一些类似

的数据框后形成我的界限
bnds = ((df['Upperbound'],df['lowerbound']))

所以文件中指定的对数量会很多。