[英]how do i use multiple columns of a df as input to a function?
ihave a dataframe full of numerical values.我有一个充满数值的 dataframe。 and i want to apply a function (delta) it takes 6 arguements.我想申请 function (delta) 它需要 6 个参数。
calls['delta'] = calls[['callput','underlyinglast','strike','yte','rfr','hvol90']].apply(delta,axis=1)
i keep getting the error我一直收到错误
TypeError: delta() missing 5 required positional arguments: 'S', 'K', 't', 'r', and 'sigma'
i also tried a variant with lambda, but i keep getting the error.我还尝试了 lambda 的变体,但我一直收到错误消息。 i think because its trying to apply the function to each individual value, instead of the row.我认为是因为它试图将 function 应用于每个单独的值,而不是行。
can i do this any other way?我可以用其他方式做到这一点吗? (without iterrows, its so slow, its a df with 500k rows) (没有 iterrows,它太慢了,它是一个有 500k 行的 df)
apply
with axis=1
calls your function for each row, but with 1 parameter: the row as a Series
object. So you either need to revise your function definition to take a single row instead of multiple parameters, or wrap your function call in a lambda function which extracts the values from each row and calls the function with them. apply
with axis=1
为每一行调用 function,但有 1 个参数:该行作为Series
object。因此,您需要修改 function 定义以采用单行而不是多个参数,或者将 function 调用包装在一个lambda function 从每一行中提取值并调用 function。
Revising your function to take a single row修改你的 function 取单行
Instead of this:而不是这个:
def delta(S, K, t, r, sigma): #...
do this:做这个:
def delta(row): S, K, t, r, sigma = row.tolist() #...
Wrapping your function call in a lambda function将您的 function 电话包装成 lambda function
Instead of this:而不是这个:
calls['delta'] = calls[['callput','underlyinglast','strike','yte','rfr','hvol90']].apply(delta,axis=1)
do this:做这个:
calls['delta'] = calls[['callput','underlyinglast','strike','yte','rfr','hvol90']].apply(lambda row: delta(*row), axis=1)
(the trick there is to use lambda row: delta(*row)
instead of just delta
; *row
basically "spreads" the items in row
across the separate arguments of delta
) (这里的技巧是使用lambda row: delta(*row)
而不仅仅是delta
; *row
基本上将row
中的项目“传播”到delta
的单独 arguments 中)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.