简体   繁体   中英

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

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

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

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

Any suggestions how to set this up, maybe with a Lambda function?

If you insist on doing things in the most convoluted way, you could use a partial as callback:

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:

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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