【发布时间】:2019-07-16 19:10:16
【问题描述】:
目标: 使用自定义 WMAPE(加权平均绝对百分比误差)函数对多个预测列和一个实际数据列进行分组,无需 for 循环。我知道输出数据帧的for循环和合并可以解决问题。我想高效地做到这一点。
有: WMAPE 功能,在数据框的一个预测列上成功使用 WMAPE 功能。一列实际数据,可变数量的预测列。
输入数据: Pandas DataFrame 包含多个分类列(City、Person、DT、HOUR)、一个实际数据列(Actual)和四个预测列(Forecast_1 ... Forecast_4)。参见 csv 链接: https://www.dropbox.com/s/tidf9lj80a1dtd8/data_small_2.csv?dl=1
需要:在 groupby 期间对多列应用 WMAPE 函数,并将预测列列表馈入 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')
输出看起来像(前两行):
所需的输出将一次性包含所有预测(Forecast_2 ... Forecast_4 的虚拟数据)。我可以已经使用 for 循环来做到这一点。我只想在 groupby 内做。我想调用一个 wmape 函数四次。如有任何帮助,我将不胜感激。
【问题讨论】:
标签: python pandas pandas-groupby forecasting pandas-apply