我在文档或 SO 上找不到任何关于此的内容......
给定:
def applied_func(row, list_of_values):
for val in list_of_values:
// do something generative
return generated_thing
list_for_applied_func = ['foo', 'bar', 'baz']
df['computed value'] = df.apply(applied_func, args=(list_for_applied_func), axis=1))
我收到意外错误“applied_func() 需要 2 个位置参数,但给出了 4 个。这告诉我它是自动解包上面的 list_of_applied_func
。如何处理传递的列表作为参数作为计算函数中使用的列表?
最佳答案
确实,如this line显示,args
是通过解包发送的,即 f(..., *args)
。补救措施是将列表转换为一元组:
# note the comma|
df.apply(applied_func, args=(list_for_applied_func,), axis=1))
这样args
将是一个1元组,当*
'ed时,将传递一个列表。
关于python - pandas .apply args 自动解压列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67507584/