DataFrame 上的 Scipy 最小化优化逐行 [英] Scipy minimisation optimisation row-wise on DataFrame

查看:56
本文介绍了DataFrame 上的 Scipy 最小化优化逐行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对时间序列中的每个时间步进行最小化优化.优化根据行中不同列中的值和一系列不等式约束来设置价格.

I need to perform a minimization optimisation for each timestep in my timeseries. The optimisation sets the price based on values in different columns across the row and a series of inequality constraints.

我的数据框在 48 年的时间序列中包含以下列:

My Dataframe has the following columns across time series of 48 years:

['CAPEX_TOT', 'CAPEX_R', 'CAPEX_WS', 'debt_BP', 'principal','interest',
   'debt_service', 'debt_EP', 'OPEX', 'OPEX_R', 'OPEX_WS',
   'DELIVERY_BAWSCA', 'DELIVERY_OTHER_DEMAND',
   'DELIVERY_SAN_FRANCISCO_CITY', 'DELIVERIES_WS', 'DELIVERIES_R',
   'PRICE_crR', 'PRICE_crWS', 'REVENUE', 'FUND_BALANCE_BP',
   'FUND_BALANCE_EP']

PRICE_crR 和 PRICE_crWS 代表纯粹基于成本回收的两种不同客户类别的价格.优化必须寻求实现成本回收(以下代码中的第一个约束条件),同时遵守以下代码中的第二个和第三个约束条件表示的几个关键策略约束.

PRICE_crR and PRICE_crWS represent the prices for two different customer classes on the basis purely of cost recovery. The optimisation must seek to achieve cost recovery (first constraint in the code below) whilst observing a couple of key policy constraints which are represented by the second and third constraints in the code below.

这是我目前所拥有的.

finance_df['revenue_R'] = finance_df.apply(lambda row: row * row.DELIVERIES_R)

约束

cons = ({'type': 'ineq', 'fun': finance_df.apply(lambda row: row - row.price_crR, axis=1)},
    {'type': 'ineq', 'fun': finance_df.apply(lambda row: ((row * row.DELIVERIES_R) - row.OPEX_R + OTHER_REVENUE)\
                                            / (debt_CAPEX_ratio * row.debt_service), axis=1)},
    {'type': 'ineq', 'fun': finance_df.apply(lambda row: (1.05 * row.price_crR) - row, axis=1)})

非负约束

bnds = ((0, None), (0, None))

一系列初始最佳猜测

price_0 = [7, 7.5, 8, 8.5, 9, 9.5, 10]

优化函数

res = minimize(finance_df['revenue_R'], price_0, method='SLSQP', bounds=bnds, constraints=cons)

运行上述脚本时,我收到以下错误消息:

When running the above script I get the following error message:

    ("'Series' object has no attribute 'DELIVERIES_R'", 'occurred at index CAPEX_TOT')

推荐答案

问题是由不正确的值引起的,finance_df.apply(lambda row: row * row.DELIVERIES_R).与跨行迭代 (DataSeries) 不同,跨表 (DataFrame) 迭代需要指定轴 = 1 如果按行,即 df.apply(fun, axis=1) 否则你获取列(轴 0)并作为您看到的列和错误.

The problem is caused by an incorrect value, finance_df.apply(lambda row: row * row.DELIVERIES_R). Unlike the iterating across a row (DataSeries), iterating across a table (DataFrame) requires the axis = 1 to be specified if row-wise, namely df.apply(fun, axis=1) else you get columns (axis 0) and as the column and the error you saw.

(回复最初作为评论给出,现在转换为答案以快速关闭这个错字问题).

(Response first given as comment, now converted to answer to close quickly this typo question).

这篇关于DataFrame 上的 Scipy 最小化优化逐行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆