Search code examples
pythonpandasdata-science

Aggregate function as an argument


I need to write a function:

def group_and_aggregate_data(df:pd.DataFrame, group_by_column:str, agg_func) -> pd.DataFrame

that groups my Excel data by city name and applies the agg_func passed as an argument. I tried this:

def group_and_aggregate_data(dataframe, cond, func):
    df_bycity = dataframe.groupby(cond).func()
    return df_bycity

but it doesn't work in Python.


Solution

  • Can you try this with df.agg():

    def group_and_aggregate_data(dataframe, cond, func):
        df_bycity = dataframe.groupby(cond).agg(func)
        return df_bycity