简体   繁体   English

在 python 中跨多行求解公式(类似于 excel)?

[英]Solving formula across multiple rows (similar to excel) in python?

I'm looking for some kind of functionality similar to excels solver in python.我正在寻找某种类似于 python 中的 excels 求解器的功能。 In python I have a function which when supplied an array of length N, returns an array of N also using some columns from a dataframe.在 python 中,我有一个 function,当它提供一个长度为 N 的数组时,它还使用 dataframe 中的一些列返回一个 N 数组。

Below is a simple example of that I have, and what the target is.下面是我所拥有的一个简单示例,以及目标是什么。

import pandas as pd

df = pd.DataFrame(
        {'Column_1' : [1,2,3,4,5],
         'Column_2' : [5,4,3,2,1],
         'Column_3' : [10,8,6,4,2]
         })

def funs(x):
    
    return(x * df['Column_1'] * df['Column_2'] * df['Column_3'])

funs(x = [1,1,1,1,1])
Out[]: 
0    50
1    64
2    54
3    32
4    10
dtype: int64

From here I am looking for a function/method that I can supply 'funs' to and a target array.从这里我正在寻找一个可以提供“乐趣”的函数/方法和一个目标数组。 The function hopefully will generate the x such that funs(x) = target. function 希望生成 x 使得 funs(x) = target。

target = [5,10,15,10,5]

y = solve_func(funs(x), target) 

funs(y) == [5,10,15,10,5]

An easier approach in this case would be to define the outcome such that x = target/(col_1 * col_2 * col_3), but a solution like this isn't as trivial in the real example, hence why I wonder if something similar to how excel solver would work exists.在这种情况下,一种更简单的方法是定义结果,使得 x = target/(col_1 * col_2 * col_3),但这样的解决方案在实际示例中并不是那么简单,因此我想知道是否类似于excel 求解器将存在。

Hope this makes sense and I really appreciate any help.希望这是有道理的,我非常感谢任何帮助。

The function scipy.optimize.fsolve finds zeros of functions, which can be used in your case as follows: function scipy.optimize.fsolve找到函数的零点,可以在您的情况下使用如下:

from scipy.optimize import fsolve

target = [5, 10, 15, 10, 5]

def residuals(x):
    """fsolve will try to make its target equal to all zeros"""
    return funs(x) - target

# Just like with Solver, you need an initial guess
initial_guess = [1, 2, 3, 4, 5]
sol = fsolve(residuals, initial_guess)

This results in sol = array([0.1, 0.15625, 0.27777778, 0.3125, 0.5]) .这导致sol = array([0.1, 0.15625, 0.27777778, 0.3125, 0.5])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM