我是python的初学者,我需要将R中的一些代码转换为Python。
我需要基于动态函数在数据集中的每一行找到一个根,R中的代码是:
library(rootsolve
library(dplyr)
library(plyr)
dataset = data.frame(A = c(10,20,30),B=c(20,10,40),FX = c("A+B-x","A-B+x","A*B-x"))
sol<- adply(dataset,1,summarize,solution_0= uniroot.all(function(x)(eval(parse(text=as.character(FX),dataset))),lower = -10000,upper = 10000,tol = 0.00001))
此代码返回[30,-10,1200]作为每行的解决方案。
在python中,我阅读了有关sciPy包优化的文档,但没有找到对我有用的代码:
我尝试了以下类似的解决方案,但没有成功:
import pandas as pd
from scipy.optimize import fsolve as fs
data = {'A': [10,30],'B': [20,40],'FX': ["A+B-x","A*B-x"]}
df = pd.DataFrame(data)
def func(FX):
return(exec(FX))
fs(func(df.FX),x0=0,args=df)
有人知道如何解决吗?
非常感谢。