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

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

我正在寻找类似于 python 中的 excels 求解器的某种功能。在 python 我有一个函数,当提供一个长度为 N 的数组时,returns 一个 N 的数组也使用数据帧中的一些列。

下面是我的一个简单示例,以及目标是什么。

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

从这里我正在寻找可以提供 'funs' 的 function/method 和一个目标数组。该函数有望生成满足 funs(x) = target.

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

y = solve_func(funs(x), target) 

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

在这种情况下,一种更简单的方法是定义结果,使 x = target/(col_1 * col_2 * col_3),但这样的解决方案是'这在真实示例中是微不足道的,因此我想知道是否存在类似于 excel 求解器工作方式的东西。

希望这是有道理的,我非常感谢任何帮助。

函数 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)

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