简体   繁体   English

Python lambda:将函数赋给另一个函数

[英]Python lambda: Assign function to another function

I have two functions, which I would like to combine: The first function called f(rdata, t) reads in the data for the time horizont t and arranges it for further modelling 我有两个函数,我想要结合起来:第一个函数叫做f(rdata,t),读取数据的时间horizo​​nt t并安排它进行进一步的建模

def f(rdata,t):
    dataset = pd.read_csv(rdata, sep = ",", skiprows = 3)
    data = dataset.loc[:,dataset.dtypes == np.float64] 
    data = pd.concat([dataset.OS_TERM, data], axis = 1).set_index(dataset.SIMULATION)
    rdata = data.loc[data["OS_TERM"] == t ].drop("OS_TERM", axis = 1).T.add_prefix("Sim_")
    return(rdata)

The second function quantile(data, q, n, ascending) calculates a hypothetical quantile q and compares it to the outcome of the first function, showing the n most extreme observations 第二个函数分位数(data,q,n,ascending)计算假设的分位数q并将其与第一个函数的结果进行比较,显示n个最极端的观察值

def quantile(data, q , n , ascending):
    name =  str(q)
    quant = pd.DataFrame({name:data.quantile(q, axis = 1)})
    quant_dif = pd.DataFrame(data.values - quant.values, columns = data.columns)**2
    cum_dif = pd.DataFrame(quant_dif.sum(axis = 0), columns = ["cum_dif"])
    out = pd.DataFrame(cum_dif.sort(["cum_dif"], ascending = ascending).ix[0:n,:])
    index = out.index.values
    sims = pd.DataFrame(data.loc[:, index])
    return(sims)

To combine the two I could built the following function 结合这两个我可以建立以下功能

quantile(f(rdata), t), q, n, ascending)

Nevertheless I would like to create a function, which reads in the data for a time horizon t, and then applies the quantile in a second step 不过我想创建一个函数,它读入时间范围t的数据,然后在第二步中应用分位数

f(data, t, quantile(data, q, n, ascending))

Any suggestions how to set this up, maybe with a Lambda function? 有任何建议如何设置,可能与Lambda函数?

If you insist on doing things in the most convoluted way, you could use a partial as callback: 如果你坚持以最复杂的方式做事,你可以使用partial作为回调:

from functools import partial

def apply(rdata, t, callback):
    data = f(rdata, t)
    return callback(data=data)


apply(rdata, t, partial(qantile, q=q, n=n, ascending=ascending))

or with a lambda: 或者用lambda:

apply(
   rdata, t, 
   lambda data, q=q, n=n, asc=ascending: qantile(data, q, n, asc)
   )

But in both cases I fail to see how it's an improvement over the plain and obvious solution... 但是在这两种情况下,我都没有看到它比简单明了的解决方案有什么改进......

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

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