![](/img/trans.png)
[英]How to average across excel rows for multiple rows using Openpyxl in Python?
[英]Solving formula across multiple rows (similar to excel) in python?
我正在尋找某種類似於 python 中的 excels 求解器的功能。 在 python 中,我有一個 function,當它提供一個長度為 N 的數組時,它還使用 dataframe 中的一些列返回一個 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
從這里我正在尋找一個可以提供“樂趣”的函數/方法和一個目標數組。 function 希望生成 x 使得 funs(x) = target。
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 求解器將存在。
希望這是有道理的,我非常感謝任何幫助。
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)
這導致sol = array([0.1, 0.15625, 0.27777778, 0.3125, 0.5])
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.