How to pass a function as a parameter to another function?

I am doing a bunch of operations on pandas dataframes. For example, finding max , min and average inside the columns and returns the column names in the new column . Now I am trying to turn 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 the current state, it also returns a description of the desired output. The fragment does not have the desired functionality and flexibility.

Setup:

# 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)

Output 1:

   col_A  col_B
0      1     20
1     20     20
2      6     20
3      1     20
4      3     20

Naive attempt:

# 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)

Output 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()? , ?

!

+3
1

, . parens . , , , , :

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
+2

Source: https://habr.com/ru/post/1683271/


All Articles