Pandas:自定义 WMAPE 函数聚合函数到多列而无需 for 循环?

Ind*_*lli 4 python forecasting pandas pandas-apply pandas-groupby

目标:在多个预测列和一个实际数据列上使用自定义 WMAPE(加权平均绝对百分比误差)函数对 Pandas 数据框进行分组,无需 for 循环。我知道输出数据帧的 for 循环和合并可以解决问题。我想有效地做到这一点。

有: WMAPE函数,成功使用WMAPE函数在dataframe的一个预测列上。一列实际数据,可变数量的预测列。

输入数据: Pandas DataFrame 具有多个分类列(City、Person、DT、HOUR)、一个实际数据列(Actual)和四个预测列(Forecast_1 ... Forecast_4)。请参阅 csv 链接:https ://www.dropbox.com/s/tidf9lj80a1dtd8/data_small_2.csv ? dl =1

需要: WMAPE 函数在 groupby 期间在多个列上应用,并将预测列列表输入 groupby 行。

所需输出:具有分类组列和 WMAPE 的所有列的输出数据框。标签是首选但不是必需的(下面的输出图像)。

到目前为止成功的代码: 两个 WMAPE 函数:一个接收两个系列并输出单个浮点值 (wmape),一个用于 groupby (wmape_gr) 的结构化:

def wmape(actual, forecast):
    # we take two series and calculate an output a wmape from it

    # make a series called mape
    se_mape = abs(actual-forecast)/actual

    # get a float of the sum of the actual
    ft_actual_sum = actual.sum()

    # get a series of the multiple of the actual & the mape
    se_actual_prod_mape = actual * se_mape

    # summate the prod of the actual and the mape
    ft_actual_prod_mape_sum = se_actual_prod_mape.sum()

    # float: wmape of forecast
    ft_wmape_forecast = ft_actual_prod_mape_sum / ft_actual_sum

    # return a float
    return ft_wmape_forecast

def wmape_gr(df_in, st_actual, st_forecast):
    # we take two series and calculate an output a wmape from it

    # make a series called mape
    se_mape = abs(df_in[st_actual] - df_in[st_forecast]) / df_in[st_actual]

    # get a float of the sum of the actual
    ft_actual_sum = df_in[st_actual].sum()

    # get a series of the multiple of the actual & the mape
    se_actual_prod_mape = df_in[st_actual] * se_mape

    # summate the prod of the actual and the mape
    ft_actual_prod_mape_sum = se_actual_prod_mape.sum()

    # float: wmape of forecast
    ft_wmape_forecast = ft_actual_prod_mape_sum / ft_actual_sum

    # return a float
    return ft_wmape_forecast

# read in data directly from Dropbox
df = pd.read_csv('https://www.dropbox.com/s/tidf9lj80a1dtd8/data_small_2.csv?dl=1',sep=",",header=0)

# grouping with 3 columns. wmape_gr uses the Actual column, and Forecast_1 as inputs
df_gr = df.groupby(['City','Person','DT']).apply(wmape_gr,'Actual','Forecast_1')
Run Code Online (Sandbox Code Playgroud)

输出看起来像(前两行):

在此处输入图片说明

所需的输出将一次性完成所有预测(Forecast_2 ... Forecast_4 的虚拟数据)。我已经可以用 for 循环来做到这一点。我只想在 groupby 中进行。我想四次调用 wmape 函数。我将不胜感激。

Ted*_*rou 6

这是一个很好的问题来展示如何在 Pandas 中优化 groupby.apply。我使用两个原则来帮助解决这些问题。

  1. 任何独立于 group 的计算都不应该在 groupby 内完成
  2. 如果有内置的groupby方法,先使用,再使用apply

让我们逐行浏览您的wmape_gr函数。

se_mape = abs(df_in[st_actual] - df_in[st_forecast]) / df_in[st_actual]
Run Code Online (Sandbox Code Playgroud)

这条线完全独立于任何组。您应该在应用程序之外进行此计算。下面我为每个预测列执行此操作:

df['actual_forecast_diff_1'] = (df['Actual'] - df['Forecast_1']).abs() / df['Actual']
df['actual_forecast_diff_2'] = (df['Actual'] - df['Forecast_2']).abs() / df['Actual']
df['actual_forecast_diff_3'] = (df['Actual'] - df['Forecast_3']).abs() / df['Actual']
df['actual_forecast_diff_4'] = (df['Actual'] - df['Forecast_4']).abs() / df['Actual']
Run Code Online (Sandbox Code Playgroud)

让我们看看下一行:

ft_actual_sum = df_in[st_actual].sum()
Run Code Online (Sandbox Code Playgroud)

该行依赖于组,因此我们必须在此处使用 groupby,但没有必要将其放置在 apply 函数中。后面会计算。

让我们转到下一行:

se_actual_prod_mape = df_in[st_actual] * se_mape
Run Code Online (Sandbox Code Playgroud)

这又是独立于组的。让我们在整个 DataFrame 上计算它。

df['forecast1_wampe'] = df['actual_forecast_diff_1'] *  df['Actual']
df['forecast2_wampe'] = df['actual_forecast_diff_2'] *  df['Actual']
df['forecast3_wampe'] = df['actual_forecast_diff_3'] *  df['Actual']
df['forecast4_wampe'] = df['actual_forecast_diff_4'] *  df['Actual']
Run Code Online (Sandbox Code Playgroud)

让我们继续看最后两行:

ft_actual_prod_mape_sum = se_actual_prod_mape.sum()
ft_wmape_forecast = ft_actual_prod_mape_sum / ft_actual_sum
Run Code Online (Sandbox Code Playgroud)

这些行再次依赖于组,但我们仍然不需要使用 apply。我们现在有 4 个 'forecast_wampe' 列中的每一个都独立于组进行计算。我们只需要将每组的每一个相加。“实际”列也是如此。

我们可以运行两个单独的 groupby 操作来对这些列中的每一列求和,如下所示:

g = df.groupby(['City', 'Person', 'DT'])
actual_sum = g['Actual'].sum()
forecast_wampe_cols = ['forecast1_wampe', 'forecast2_wampe', 'forecast3_wampe', 'forecast4_wampe']
forecast1_wampe_sum = g[forecast_wampe_cols].sum()
Run Code Online (Sandbox Code Playgroud)

我们得到以下 Series 和 DataFrame 返回

在此处输入图片说明

在此处输入图片说明

然后我们只需要将 DataFrame 中的每一列除以系列。我们需要使用div方法来改变分区的方向,以便索引对齐

forecast1_wampe_sum.div(actual_sum, axis='index')
Run Code Online (Sandbox Code Playgroud)

这将返回我们的答案:

在此处输入图片说明


wil*_*llk 4

如果您修改wmape为使用广播来处理数组,那么您可以一次性完成:

def wmape(actual, forecast):
    # Take a series (actual) and a dataframe (forecast) and calculate wmape
    # for each forecast. Output shape is (1, num_forecasts)

    # Convert to numpy arrays for broadasting
    forecast = np.array(forecast.values)
    actual=np.array(actual.values).reshape((-1, 1))

    # Make an array of mape (same shape as forecast)
    se_mape = abs(actual-forecast)/actual

    # Calculate sum of actual values
    ft_actual_sum = actual.sum(axis=0)

    # Multiply the actual values by the mape
    se_actual_prod_mape = actual * se_mape

    # Take the sum of the product of actual values and mape
    # Make sure to sum down the rows (1 for each column)
    ft_actual_prod_mape_sum = se_actual_prod_mape.sum(axis=0)

    # Calculate the wmape for each forecast and return as a dictionary
    ft_wmape_forecast = ft_actual_prod_mape_sum / ft_actual_sum
    return {f'Forecast_{i+1}_wmape': wmape for i, wmape in enumerate(ft_wmape_forecast)}
Run Code Online (Sandbox Code Playgroud)

apply然后在适当的列上使用:

# Group the dataframe and apply the function to appropriate columns
new_df = df.groupby(['City', 'Person', 'DT']).apply(lambda x: wmape(x['Actual'], 
                                        x[[c for c in x if 'Forecast' in c]])).\
            to_frame().reset_index()
Run Code Online (Sandbox Code Playgroud)

这会产生一个具有单个字典列的数据框。 中间结果

单列可以转换为多列以获得正确的格式:

# Convert the dictionary in a single column into 4 columns with proper names
# and concantenate column-wise
df_grp = pd.concat([new_df.drop(columns=[0]), 
                    pd.DataFrame(list(new_df[0].values))], axis=1)
Run Code Online (Sandbox Code Playgroud)

结果:

运算结果