如何将一个函数作为参数传递给另一个函数? [英] How to pass a function as a parameter to another function?
问题描述
我正在对熊猫数据帧进行大量操作.例如,在列内找到 max , min 和平均值,并找到
I'm doing a bunch of operations on pandas dataframes. For example finding max, min and average inside columns and return the column names in a new column. Now I'm trying to wrap these things into a function, and use max()
and/or min()
as arguments in this function.
下面是一个片段,以非常简单的方式描述了我要执行的操作.在其当前状态下,它还返回所需输出的描述.但是,该代码片段没有所需的功能和灵活性.
Below is a snippet that describes what I'm trying to do in a very simplified way. In its current state it also returns a description of the desired output. The snippet does not have the desired functionality and flexibility though.
# Sample dataframe
df = pd.DataFrame({'col_A':[1,20,6,1,3]})
def findValue(function, df, colname):
print(function) # just a placeholder
df[colname] = df.max()[0]
return df
df2 = findValue(function='max', df=df, colname='col_B')
print(df)
输出1:
col_A col_B
0 1 20
1 20 20
2 6 20
3 1 20
4 3 20
天真尝试:
# Sample dataframe
df = pd.DataFrame({'col_A':[1,20,6,1,3]})
# The function I would like to use in another function is max()
# My function
def findValue(function, df, colname):
df[colname] = df.function()[0]
return df
df2 = findValue(function=max(), df=df , colname='col_B')
print(df)
输出2:
Traceback (most recent call last):
File "<ipython-input-7-85964ff29e69>", line 1, in <module>
df2 = findValue(function=max(), df=df , colname='col_B')
TypeError: max expected 1 arguments, got 0
如何更改上面的代码段,以便可以将 function = max()
更改为 function = min()
或参数中的任何其他函数> findValue()
?甚至定义要以类似方式使用的功能列表?
How can I change the above snippet so that I can change function = max()
to function = min()
or any other function in the arguments of findValue()
? Or even define a list of functions to be used in a similar manner?
谢谢您的任何建议!
推荐答案
您非常,非常亲密.在传递函数时,您几乎只需要删除paren.这是一个简化的示例,它遍历函数名列表,并且看起来可以满足您的要求:
You are very, very close. You pretty much just need to remove the parens when passing in the function. Here's a simplified example that loops over a list of function names, and appears to do what you want:
def findValue(func, x, y):
return func(x, y)
for calc in (max, min):
result = findValue(func=calc, x=1, y=10)
print(result)
输出:
10
1
这篇关于如何将一个函数作为参数传递给另一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!