简体   繁体   English

如何在另一个函数中将Python pandas函数作为变量/参数传递?

[英]How to pass a Python pandas function as a variable/parameter in another function?

import pandas as pd

def func_sum(df, cols, col):
    res = df[cols].groupby(col).sum()
    return res

def func_count(df, cols,col):
    res = df[cols].groupby(col).count()
    return res

def func_ave(df, cols, col):
    res = df[cols].groupby(col).mean()
    return res

The way I did to combine these three functions is like below, which is not very elegant. 我将这三个功能结合在一起的方式如下所示,这不是很优雅。

def func(df, cols, col, method):
    if method == 'sum':
        return df[cols].groupby(col).sum()
    if method == 'count':
        return df[cols].groupby(col).count()
    if method == 'mean':
        return df[cols].groupby(col).mean()

I wonder if there is a better way to do this without using IF ELSE statement. 我想知道是否有更好的方法而不使用IF ELSE语句。 How Can I Pass the function of (sum, count, or mean) as a variable and then let's the passed function variable to be called inside the main 'func' function. 如何将(求和,计数或均值)函数作为变量传递,然后让传递的函数变量在主“ func”函数中调用。

I would greatly appreciate any suggestions. 我将不胜感激任何建议。

Use groupby.agg , which takes one or more functions by reference or by name. 使用groupby.agg ,它通过引用或名称接受一个或多个功能。

For example: 例如:

def func(df, cols, col, method):
    return df[cols].groupby(col).agg(method)

func(df, cols, col, pd.Series.sum)
func(df, cols, col, 'count')
func(df, cols, col, np.mean)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将参数列表传递给Python中的另一个函数? - How to pass a parameter list to another function in Python? 如何在 python 中将变量作为另一个 function 的参数传递 - How to pass a variable as an argument of another function in python 如何将python事件变量传递给另一个函数? - How to pass a python event variable into another function? 如何将带有参数的 function 作为参数传递给 Python 中的另一个 function? - How pass a function with parameters as a parameter to another function in Python? 将函数参数作为参数传递给python中的另一个函数 - pass a function parameter as an argument to another function in python python - 如何在python pandas管道中将函数作为参数传递给参数 - How can I pass function as argument with parameter in python pandas pipe 如何将变量从一个 function 传递到 python 中的另一个 function - How to pass a variable from one function to another function in python 如何在 python 中将一个变量作为另一个变量传递给 function - How to pass one variable as another variable in a function in python 如何在jinja循环中将单个jinja变量传递给python函数作为参数? - How to pass individual jinja variable in a jinja loop to python function as a parameter? 如何将mean()作为输入参数传递给Python中的另一个函数? - How to pass mean() as input parameter to another function in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM